需要增量写入文件的功能

时间:2013-01-25 19:50:06

标签: r

我有一个生成模拟数据并将其写入csv文件的函数。这工作正常,但在函数完成之前它不会写出文件。我希望它在每个for循环结束时写一个文件。任何提示都非常感谢。

截断的代码块:

for (m in 1:M){

simulation code....

write.csv(userDF, file=filename, row.names=FALSE) 
} 

2 个答案:

答案 0 :(得分:4)

有一个flush功能。您可能需要引用某种连接类型,或许

for (m in 1:M){
  simulation code....
  filx=file("filename")
  write.csv(userDF, file=filx, row.names=FALSE) 
  flush(filx)
} 

答案 1 :(得分:0)

我这样做是为了在每次迭代中将其追加到相同的增长文件中。肯定是在写每个循环!

library(readr)
startfile=TRUE  
for(index in 1:9){

  ... # make your dataframe here

  ## The first time through the loop, don't append. 
  ## Also, this will write the column names

  write_csv(as.data.frame(result),"result.csv", append=!startfile)

  ## On subsequent iterations, append your dataframe to the file
  startfile=FALSE
  } 

library(readr) startfile=TRUE for(index in 1:9){ ... # make your dataframe here ## The first time through the loop, don't append. ## Also, this will write the column names write_csv(as.data.frame(result),"result.csv", append=!startfile) ## On subsequent iterations, append your dataframe to the file startfile=FALSE }