0

我正在阅读大约 50 个 csv 文件(相同的命名约定,相同的结构,每个文件大约 150k 行)。然后我还想合并所有文件,但我希望能够识别每一行的原始来源。

到目前为止,我的解决方案是根据 list.files 读取所有数据,然后将它们与 rbindlist 和 idcol 参数合并在一起。但是我在设置 idcol 参数时遇到了麻烦,以便它采用原始 data.table 的名称。此外,我不知何故努力将我的表定义为 rbindlist 的有效列表。

    #get filenames + path
    temp=list.files(path="C:/LocalData",pattern="RV_*",full.names=TRUE)

    #get filenames without path
    temp2=list.files(path="C:/LocalData",pattern="RV_*",full.names=FALSE)

    # get a substring of names to create a new list for the tbl names
    filenames=sapply(temp2,function(x) substr(x,1,5)) 

    #read in all files via fread and store it as an own data.table
    for (i in 1:length(temp)) assign(filenames[i], fread(temp[i])) 

    #now bring all data.tables together and create a new column that indicates the source
    RV=rbindlist(as.list(filenames),idcol = TRUE)
      Error in rbindlist(as.list(filenames), idcol = TRUE) : 
      Item 1 of list input is not a data.frame, data.table or list

    #if I state the dts individually it works
    RV=rbindlist(list(RV_v1,RV_v2,RV_v3,RV_v4,RV_v5),idcol = TRUE)

如何根据我的“文件名”变量为 rbindlist 定义一个列表?

此外 - 而不是在新创建的.id 列中只有一个数值,我想拥有原始 data.table 的值,例如 RV_v1 和 RV_v2 我怎样才能做到这一点?

> RV[6:15]
    .id Identifier Name       Value
 1:   1          F   AF 68,77523568
 2:   1          G   AG 30,28675331
 3:   2          A   AA 71,38992413
 4:   2          B   AB 86,87556292
 5:   2          C   AC 60,81629287
 6:   2          D   AD 5,815721308
 7:   2          E   AE  11,9030038
 8:   2          F   AF 56,28142304
 9:   2          G   AG 3,291405727
10:   3          A   AA 59,62673465
> 

In R, add NEW column to MULTIPLE df using df names已经提出并回答了一个类似的问题, 但我无法以某种方式对其进行修改,因此它对我有用..

为了能够重现我的问题,我上传了 5 个 csv 文件的样本。https://www.dropbox.com/s/qst2rgjkb0kpori/RVs.zip?dl=0 提前谢谢!

编辑:按照弗兰克的建议

rbindlist(lapply(setNames(temp, substr(temp2, 1, 5)), fread), idcol=TRUE)

可以很好地做我想做的事情。谢谢!

4

0 回答 0