[R] write.table and append

Louis Aslett laslett at louisaslett.com
Fri Feb 8 16:06:01 CET 2013


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



More information about the R-help mailing list