简体   繁体   English

R保存数据。每次迭代

[英]R save data.frame each iteration

I have a loop for a data frame construction, and I would like to write all small pieces at each iteration in a csv file. 我有一个用于数据帧构造的循环,我想在每次迭代时将所有小片段写到一个csv文件中。 Something like a rbind() but in a file... 有点像rbind()但在文件中...

I have seen sink() like that 我已经看到过这样的sink()

exemple : 例子:

sink("resultat/output.txt")
df.total<-NULL
for(i in 1:length(list2.1)){
  if(i%%100==0){print(i)}
  tps<-as.data.frame(list2.1[i])
  tps<-cbind(tps,as.data.frame(list2.2[i]))
  colnames(tps)<-c("slope","echange")
  tps$Run<-rep(data$run_nb[i],length(tps$slope))
  tps$coefSlope<-rep(data$coef_Slope_i[i],length(tps$slope))
  tps$coefDist<-rep(data$coef_dist_i[i],length(tps$slope))
  sink(tps)
  df.total<-rbind(df.total,tps)
}
sink()
write.csv(df.total,"resultat/df_total.csv")

but I don't think it work for my case ... any suggestions 但我认为这不适用于我的情况...任何建议

You can use sink (which redirects R output to a connection) along with print 您可以将接收sink (将R输出重定向到连接)与print一起使用

df <- data.frame(a = 0:1, b = 1:2)
sink("output.txt")
for(i in 1:10) {
    print(df[i+2, ] <- c(sum(df$a), tail(df$b, 1) + 1))
    ## Or, to save the whole data.frame each time: print(df)
}
sink()

Another option is to use cat 另一种选择是使用cat

df <- data.frame(a = 0:1, b = 1:2)
for(i in 1:10) {
    cat(df[i+2, ] <- c(sum(df$a), tail(df$b, 1) + 1), "\n", file="output.txt" append=TRUE)
}

You can also use write.table to save the whole data.frame 您还可以使用write.table保存整个data.frame

df <- data.frame(a = 0:1, b = 1:2)
for(i in 1:10) {
    df[i+2, ] <- c(sum(df$a), tail(df$b, 1) + 1)
    write.table(df, file="output.txt", append=TRUE)
}

If you set append = FALSE only the last iteration will be saved. 如果将append = FALSE设置append = FALSE仅保留最后一次迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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