Skip to content

write.table and append

5 messages · Brian Smith, Louis Aslett, Ben Tupper

#
I believe your problem stems from using ifelse() actually ... it
requires the statements which it runs to return a value with the same
shape as the test, which write.table() isn't doing.

Just change it to a regular if with an else and you'll be fine:

for(i in 1:2){
  mat <- data.frame(sample(1:30,9),3,3)
  colnames(mat) <- letters[1:3]
  if(i == 1){
    write.table(mat,paste('test.txt',sep=''),row.names=F)
  } else {
    write.table(mat,paste('test.txt',sep=''),row.names=F,col.names=F,append=TRUE)
  }
}

Hope that helps,

Louis
On Fri, Feb 8, 2013 at 2:40 PM, Brian Smith <bsmith030465 at gmail.com> wrote:
#
Hi,
On Feb 8, 2013, at 9:40 AM, Brian Smith wrote:

            
You might try assign each parameter based upon the value of i instead of trying to manage two different calls to write.table through an ifelse function.  ifelse doesn't seem to like the value returned by write.table (NULL).  Here's a simply example...
Error in ifelse(TRUE, NULL, NULL) : replacement has length zero
Error in ifelse(FALSE, NULL, NULL) : replacement has length zero

I think that is what the warning in ?ifelse is alluding to.  You would only know that write.table returns NULL if you have bitten by it before.  I have bite marks.

for(i in 1:2){
   mat <- data.frame(sample(1:30,9),3,3)
   colnames(mat) <- letters[1:3]
   write.table(mat, file = "test.txt", 
      row.names = FALSE,
      col.names = (i == 1),
      append = (i != 1) )       
}


Cheers,
Ben
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org