简体   繁体   中英

“For” loop than overwrites when using write.table

I am trying to extract every two consecutive columns from an array, writing a .dat with every pair. The problem is that, when using write.table() it overwrites the files. When I use print() instead of write.table() it shows the correct subsets, though.

I also need the file names to show the number of the pair of columns selected (a total of 6 pairs), as well as the number of the dimension (from 1 to 5). For this I have used an easier solution such as tagging 1:30.

for(i in 0:5) {
  for (j in 1:5) {
    for (k in 1:30) {
      filename <- paste("Component",k, ".dat", sep="")
      write.table(data[,c(2*i+1,2*i+2),j],col.names=F, row.names=F, sep= " ")    
    } 
  }
}

Any hints why it does not work? I hope my goal is understandable. Thanks a lot for your time!

Set the argument append to TRUE :

write.table(data[,c(2*i+1,2*i+2),j], 
            file=filename, 
            append=TRUE,
            col.names=F, 
            row.names=F, 
            sep= " ")

also, as correctly pointed out by @Roland, you have forgotten to pass the file argument (already added in my example above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM