How to add column data to csv file using R?

I have information contained in vectors, for example:

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

I want to add this data to a file, so I use:

 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 problem is that this is added to one column, for example:

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

I want to add this data to the columns so that they end like this:

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

How can I do this using R?

+7
source share
4 answers

write.table writes a file or data.frame matrix to a file. If you want two to write a file with two columns of data.frame (or matrix) to the 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 pointed out by @JoshuaUlrich's comment, this is not a R problem, you cannot add a column to the csv file because of how it is stored on disk.

+6
source

While you cannot add a column directly to the file, you can read it in the data.frame file, add a 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") 
+7
source

If you want to write a file along the way (for example, in a loop):

 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 everything at once:

 test<-t(rbind(seq1,seq2)) write.csv(test, "test.csv") 
+2
source

Check out 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.

+2
source

All Articles