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?
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With