Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data by columns in csv file using R?

Tags:

append

r

csv

I have information that is contained in vectors, for example:

sequence1<-seq(1:20)
sequence2<-seq(21:40)
...

I want to append that data to a file, so I am using:

write.table(sequence1,file="test.csv",sep=",",append=TRUE,row.names=FALSE,col.names=FALSE)
write.table(sequence2,file="test.csv",sep=",",append=TRUE,row.names=FALSE,col.names=FALSE)

But the issue is that this is added all in one column like:

1
2
3
...
21
22
...
40

I want to add that data in columns so that it ends up like:

1         21
2         22
3         23
...       ...
20        40

How I can do that using R?

like image 201
Layla Avatar asked Oct 26 '12 00:10

Layla


2 Answers

While you cannot add the column directly on the file, you can read it into a data.frame, append to column to it, and write the result as a csv file:

tmp <- read.csv("original_file.csv")
tmp <- cbind(tmp, new_column)
write.csv(tmp, "modified_file.csv")
like image 187
Eduardo Tabacman Avatar answered Nov 14 '22 01:11

Eduardo Tabacman


write.table writes a data.frame or matrix to a file. If you want two write a two-column data.frame (or matrix) to a file using write.table, then you need to create such an object in R

x <- data.frame(sequence1, sequence2)
write.table(x, file = 'test.csv', row.names=FALSE,col.names=FALSE)

See ?write.table for a very clear description of what the function does.

As stated by @JoshuaUlrich's comment, this is not really an R issue, you can't append a column to a csv file due to the way it is stored on disk.

like image 25
mnel Avatar answered Nov 14 '22 02:11

mnel