[R] write.table and append

Ben Tupper btupper at bigelow.org
Fri Feb 8 16:18:47 CET 2013


Hi,

On Feb 8, 2013, at 9:40 AM, Brian Smith wrote:

> Hi,
> 
> I am trying to append tables on file with this sample code:
> 
>        for(i in 1:2){
>            mat <- data.frame(sample(1:30,9),3,3)
>            colnames(mat) <- letters[1:3]
>            ifelse(i ==
> 1,write.table(mat,paste('test.txt',sep=''),row.names=F),
> 
> write.table(mat,paste('test.txt',sep=''),row.names=F,col.names=F,append=TRUE))
>        }
> 
> However, this gives an error:
> 
> "Error in ifelse(i == 1, write.table(mat, paste("test.txt", sep = ""),  :
>  replacement has length zero"
> 
> - Should I be passing in some other parameters or using a different
> function to append tables to file?


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

> ok <- ifelse( TRUE, NULL, NULL)
Error in ifelse(TRUE, NULL, NULL) : replacement has length zero
> ok <- ifelse( FALSE, NULL, NULL)
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

> 
> thanks!
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

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



More information about the R-help mailing list