【问题标题】:Read multiple csv into one and add a new column based on the file names将多个csv读入一个并根据文件名添加一个新列
【发布时间】:2021-07-15 12:34:01
【问题描述】:

使用此选项可以将特定路径的所有 csv 读取到一个数据帧中 图书馆(dplyr) 库(字符串)

library(data.table) 

setwd("C:/Users/User/Desktop/myfile")
files <- list.files(path = "C:/Users/User/Desktop/myfile",pattern = ".csv")
temp <- lapply(files, fread, sep=",")
data <- rbindlist( temp )

什么命令最适合添加每行都有文件名的列?

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用sapply 读取列表中的所有文件,并使用rbindlist 将它们组合成一个数据框,其中包含一个新列filename,其中每一行都有文件的名称。

    library(data.table)
    result <- rbindlist(sapply(files, fread,simplify = FALSE), idcol = 'filename')
    

    【讨论】:

      【解决方案2】:

      您想为每个 data.frame 添加一列,并带有文件名?

      在rbindlist之前做一下怎么样?

      temp <- lapply(files,fread,sep=",")
      temp <- for(i in seq_along(temp)) temp[[i]] = cbind(File=files[i],temp[[i]])
      data <- rbindlist( temp )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-03
        • 2017-04-21
        • 2023-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多