8

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Layla
  • 5,234
  • 15
  • 51
  • 66
  • 3
    You can't append columns to a CSV file. You have to re-write every row each time you want to add a column. This has nothing to do with R; it's how the file is stored on-disk. – Joshua Ulrich Oct 26 '12 at 00:55

4 Answers4

12

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")
sherminds
  • 77
  • 6
6

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.

mnel
  • 113,303
  • 27
  • 265
  • 254
3

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")
sherminds
  • 77
  • 6
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.

Shivpe_R
  • 1,022
  • 2
  • 20
  • 31