Search code examples
rcsvcreatefile

Undesirable alignment when writing csv file using write.table in R


I am trying to write and append my output to a csv file using R. First, the program will write the header and then inside a for loop append the generated rows. An example code is as follows:

   writeLines(text=c('Mean','Sd','\n'),'file.csv',sep=',')
   for(i in 1:5)
    {x <- rnorm(10); dat1 <- cbind(mean(x),sd(x))
      write.table(dat1,'file.csv',append=TRUE,sep=',',col.names=FALSE)
    }

But this shifts my first row to right by one element giving the following in csv output. How can I avoid this? Is there another way to achieve what I am trying to do here?

EDIT Also, how do we remove the column labeling which is 1 in this case? col.names=FALSE does not seem to help. I used row.names=FALSE as suggested by @Roman Luštrik. It solved this problem. But the first row shifting problem is not yet to be addressed.

enter image description here


Solution

  • Why not use paste()?

    writeLines(text=paste(c('Mean','Sd'),collapse=','),'file.csv',sep="\n")
    for(i in 1:5) {
      x <- rnorm(10); dat1 <- cbind(mean(x),sd(x))
      write.table(dat1, 'file.csv', append=TRUE, sep=',', row.names=FALSE, col.names=FALSE)
    }