【问题标题】:Add column corresponding to file of origin when reading in many csv files in R在R中读取许多csv文件时添加与原始文件对应的列
【发布时间】:2020-05-04 06:33:38
【问题描述】:

我正在将列表中的 csv 文件读入一个数据集中,使用

x <- do.call(rbind, lapply(list, fread))

我想在x 中添加一列,表示每一行对应的文件名。

list 看起来像这样:

[[1]] '~/amsterdam.csv'
[[2]] '~/atlanta.csv'
[[3]] '~/bangalore.csv'

我希望x 看起来像这样

 V1   V2           city
2.5   3.4   '~/amsterdam.csv'
5.4   1.1   '~/bangalore.csv'
3.4   2.9   '~/atlanta.csv'
0.5   9.8   '~/bangalore.csv'

有没有办法通过我使用的命令将 x 的每一行链接到它所源自的文件?

我目前正在使用循环来执行此操作(读取文件,然后添加与文件名对应的列,然后将所有文件绑定在一起),但我想知道是否有更快更清洁的方法来做到这一点.

【问题讨论】:

    标签: r csv fread


    【解决方案1】:

    如果您使用的是data.table,请尝试使用rbindlist 而不是do.call(rbind...。您可以使用idcol 参数添加一个新列City,该参数将为每个数据帧提供一个索引,稍后可以从@ 指定值987654326@。另请注意,list 是 R 中的内部函数,最好避免将其用作变量名。

    library(data.table)
    
    x <- rbindlist(lapply(list, fread), idcol = "City")
    x[, City := basename(list)[City]]
    

    【讨论】:

      【解决方案2】:

      我觉得这应该可行:

      myFread <- function(fileName){
          data.frame(
              fread(fileName)
              , "city" = fileName
          )
      }
      

      当然还有这个

      x <- do.call(rbind, lapply(list, fread))
      

      【讨论】:

        猜你喜欢
        • 2017-07-25
        • 1970-01-01
        • 2017-03-09
        • 2011-08-11
        • 1970-01-01
        • 2017-05-09
        • 2016-06-14
        • 2017-08-03
        相关资源
        最近更新 更多