在for循环中写入.csv [英] Write .csv in a for loop
问题描述
我想在for循环中写csv文件。说我有一个数据框架 data
有3行,为了简单,变量 x
。最后,我希望我的输出是200个.csv文件,每个文件包含一行数据。数据的第一列是我的变量的标识(ID)。
I want to write csv files in a for loop. Say I have a data frame data
with 3 rows, to make it simple, of a variable x
. In the end, I want my output to be 200 .csv files, each one containing a row of the data. The first column of the data is the identification ("ID") of my variables.
此外,我的数据描述如下:
Furthermore, my data is described as the following:
data:
ID x
[1] a 1
[2] b 2
[3] c 3
for (i in nrow(data)){
write.csv(data[i,2], file = paste0("Directory/", "data[i,1], ".csv"))
}
我运行此代码并创建一个csv文件,但只创建最后一行,我发现只有一个文件 c.csv
。
I run this code and a csv file is created. However, only the last row is created, meaning that I'm found with only one file c.csv
.
你知道我做错了吗?
推荐答案
没有,我们可以自动创建所有的档案需要使用一个循环,你可以使用 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 fwrite
is still in the development version of data.table 1.9.7
. Go here for install instructions.
这篇关于在for循环中写入.csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!