首页 > 解决方案 > 读取并绑定多个保存文档 ID 的 csv 文件

问题描述

我正在尝试读取具有相同结构的文件夹中的多个 csv 文件,并且我发现zx8754 解决了这个问题,就像我需要的那样,但我意识到我必须在每个表上保留和 id 才能得到类似下面的内容文件

abc <- structure(c("1", "1", "1", "2", "2", "2", "3", "3", "3", "a", 
"a", "a", "b", "b", "b", "c", "c", "c", "a", "a", "a", "b", "b", 
"b", "c", "c", "c", "a", "a", "a", "b", "b", "b", "c", "c", "c"
), .Dim = c(9L, 4L))

我能否轻轻地获得一些指导,以便在为文件夹中的每个 csv 添加 id 列的东西中打开下面的代码?

myMergedData <- 
  do.call(rbind,
          lapply(list.files(path = "N:/Ring data by cruise"), read.csv))

提前致谢!

标签: rcsvdata-binding

解决方案


您可以使用创建idmap_df

myMergedData <- purrr::map_df(list.files(path = "N:/Ring data by cruise"), 
                              read.csv, .id = 'id')

如果您想在基础 R 中执行此操作:

data <- lapply(list.files(path = "N:/Ring data by cruise"), read.csv)
myMergedData <- Map(cbind, data, id = seq_along(data))

推荐阅读