How to add data by columns in csv file using R?
Solution 1
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.
Solution 2
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")
Solution 3
Check on the following code,
seq1 <- seq(1:20)
seq2 <- seq(21:40)
bind <- cbind(seq1,seq2)
write.csv(bind,file = "Your_path", append = TRUE)
This Code Works.
Solution 4
If you want to write the file as you go (in a loop for example):
seq1<-t(seq(1,20,1))
seq2<-t(seq(21,40,1))
write.table(seq1,"test.csv",sep=",",append=TRUE,row.names=FALSE,col.names=FALSE)
write.table(seq2,"test.csv",sep=",",append=TRUE,row.names=FALSE,col.names=FALSE)
Then transpose the file at the end. If you want to do it all at once:
test<-t(rbind(seq1,seq2))
write.csv(test, "test.csv")
Layla
Updated on July 21, 2022Comments
-
Layla almost 2 years
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?