使用 Reduce 合并 R 中的许多表时使用文件名重命名列

Rename columns with filenames while merging many tables in R using Reduce

我这样阅读我所有的文件:

tables <- lapply(files, function(x) read.table(x, col.names=c("unit","count")))

我稍后将使用列 unit 合并它们。但是,我希望可以使用变量 files 中的原始文件名作为第二列,而不是 count。那是因为我稍后会像这样执行合并:

MyMerge <- function(x, y){
  df <- merge(x, y, by="unit", all.x= TRUE, all.y= TRUE)
  return(df)
}

data <- Reduce(MyMerge, tables)

这会导致问题,因为 merge 函数无法处理超过 3 个非唯一列名称(它们变为 count.x、count.y 并计数,因此我的脚本无法处理超过 3 个文件).

它应该像做一样简单:

tables <- lapply(files, function(x) read.table(x, col.names=c("unit", x)))

也许您还想在将文件名添加为列名之前稍微清理一下文件名,例如:

col.names=c("unit", gsub('\.csv', '', x))

如果您想从库名或类似名称中删除 .csv