如何将 dplyr 组写入单独的文件? [英] How can I write dplyr groups to separate files?
问题描述
我正在尝试为使用 dplyr 的 group_by 函数分组的数据框中的每个组创建单独的 .csv 文件.到目前为止,我有类似的东西
I'm trying to create separate .csv files for each group in a data frame grouped with dplyr's group_by function. So far I have something like
by_cyl <- group_by(mtcars, cyl)
do(by_cyl, write_csv(., "test.csv"))
正如预期的那样,这会写入一个仅包含最后一组数据的 .csv 文件.如何修改它以写入多个 .csv 文件,每个文件的文件名都包含 cyl?
As expected, this writes a single .csv file with only the data from the last group. How can I modify this to write multiple .csv files, each with filenames that include cyl?
推荐答案
您可以将 csv 写入过程包装在自定义函数中,如下所示.请注意,该函数必须返回一个 data.frame
否则返回错误 Error: Results are not data frames at position
You can wrap the csv write process in a custom function as follows. Note that the function has to return
a data.frame
else it returns an error Error: Results are not data frames at positions
这将返回 3 个名为mtcars_cyl_4.csv"、mtcars_cyl_6.csv"和mtcars_cyl_8.csv"的 csv 文件
This will return 3 csv files named "mtcars_cyl_4.csv","mtcars_cyl_6.csv" and "mtcars_cyl_8.csv"
customFun = function(DF) {
write.csv(DF,paste0("mtcars_cyl_",unique(DF$cyl),".csv"))
return(DF)
}
mtcars %>%
group_by(cyl) %>%
do(customFun(.))
这篇关于如何将 dplyr 组写入单独的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!