【问题标题】:Create multiple csv extracts by subsetting data frame通过子集数据框创建多个 csv 提取
【发布时间】:2017-02-23 00:19:03
【问题描述】:

我已经搜索了许多问答,但尚未找到解决此问题的方法...(请参阅下面的尝试)

我有一个交易数据集MAC_trans_sales_members,其中每笔交易都分配给一个客户 ID,每个客户分配给一个同类群组,例如join.cohort列中的“01/2016”。对于 1 个 excel 文件,有 400 万客户太多行,所以我想为每个加入队列创建单独的子集,并将每个子集导出到单独的 csv。大约有 18 个群组,所以我想自动化这个子集。

我尝试了以下几段代码,但都不起作用:

尝试 1

dt <- MAC_trans_sales_members
setDT(dt)[, fwrite(.SD, paste0("output_", join.cohort,".csv")), 
      by = join.cohort, .SDcols=names(dt) ]

Error: is.character(file) && length(file) == 1 && !is.na(file) is not TRUE

尝试 2

setDT(MAC_trans_sales_members)[, write.csv(.SD, paste0("output_", join.cohort,".csv")), 
by = join.cohort, .SDcols=names(MAC_trans_sales_members) ]

Error in file(file, ifelse(append, "a", "w")) : 
invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :
the condition has length > 1 and only the first element will be used

尝试 3

daply(MAC_trans_sales_members, .(join.cohort), write.csv)

...只是在控制台中喷出几行数据

我做错了什么??

【问题讨论】:

    标签: r loops subset export-to-csv


    【解决方案1】:

    join.cohort 是您代码中j 中的一个向量。使用unique

    MAC_trans_sales_members[, 
        fwrite(.SD, paste0("output_", unique(join.cohort), ".csv")),
        by=join.cohort]
    

    对于您的尝试 3,未传入 write.csvfile 参数。

    【讨论】:

    • 谢谢 - 通过添加 unique 进行了更改,但现在我仍然收到错误消息:Error in fwrite(.SD, paste0("output_", unique(join.cohort), ".csv")) : No such file or directory: 'output_02/2016.csv'. Unable to create new file for writing (it does not exist already). Do you have permission to write here, is there space on the disk and does the path exist? 有什么想法吗?
    • 文件路径 output_02/2016.csv 必须存在才能正常工作。检查文件夹 output_02 是否在您的工作目录中,您可以使用 'getwd()' 进行检查
    • 谢谢 - join.cohort 中的变量格式为 01/2016、02/2016 等,因此输出代码将“/”作为文件夹级别。我将“/”重写为“-”,现在它可以很好地导出,而且速度如此之快!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多