且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在for循环中写入.csv

更新时间:2022-04-02 08:35:45

没有,我们可以自动创建所有的档案需要使用一个循环,你可以使用 data.table 方法,这将更高效,更快。

No need to use a loop. You can use a data.table approach, which will be more efficient and faster.

library(data.table)

# create a column with row positions
setDT(dt)[, rowpos := .I]

# save each line of your dataset into a separate .csv file
dt[, write.csv(.SD, paste0("output_", rowpos,".csv")), 
                  by = rowpos, .SDcols=names(dt) ]

/ strong>

Making things much faster

# Now in case you're working with a large dataset and you want
# to make things much faster, you can use `fwrite {data.table}`*

dt[, fwrite(.SD, paste0("output_", rowpos ,".csv")), 
               by = rowpos, .SDcols=names(dt) ]

>

Using a Loop

# in case you still want to use a loop, this will do the work for you:

for (i in 1:nrow(dt)){
                      write.csv(dt[i,], file = paste0("loop_", i, ".csv"))
                      }

额外:保存 dataframe 按组而不是按行

Extra: Saving subsets of dataframe by groups instead of by rows

# This line of code will save a separate `.csv` file for every ID 
# and name the file according to the ID


 setDT(dt)[, fwrite(.SD, paste0("output_", ID,".csv")), 
                       by = ID, .SDcols=names(dt) ]

*
ps。注意 fwrite 仍然在 data.table 1.9.7 的开发版本中。请访问此处查看安装说明。

* ps. note that fwriteis still in the development version of data.table 1.9.7. Go here for install instructions.