简体   繁体   中英

How to append using write.table but only have col.names appear once (at top of output file)?

I have a loop that creates/appends to a csv. I'm using write.table(df, "file.csv", sep=",", append=T, col.names=T) inside the loop (it is necessary to write to disk each loop iteration for unrelated reasons).

Now this repeats the column names each time it appends (understandably, since that's what it has been instructed to do).

With some sort of logic, the repeated headers can be avoided eg

if(!exists("file.csv")) { 

  # Provide col names first time only
  write.table(df, "file.csv", sep=",", append=T, col.names=T) 

  } else {

  # Don't provide col names beyond the first time
  write.table(df, "file.csv", sep=",", append=T) 

}

Is there something (much) simpler?

您可以一口气做到这一点:

write.table(df, "file.csv", append=T, col.names=!file.exists("file.csv"))

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