Match files names in a directory with names in a dataframe column - 将匹配的行粘贴为匹配文件中的列

Match files names in a directory with names in a dataframe column - Paste matched row as columns in the matched file

我在一个文件夹中有 100 个 files.txt。

那些 filenames.txt 被相同地写入 R 数据帧的 column1 行。

files.txt 少于数据框 column1 行!这意味着并非 column1 的所有行都会匹配!

我想做什么:

如果文件名与第 1 列名称匹配,则将第 2 列和第 3 列的名称插入同一行(R 数据框),这与 file.txt.

中的列相同

例子

Name   Family  Subfamily
marc    A        B
Jaco    C        D
marc.txt   
Jaco.txt 

包含新列系列和子系列的输出 files.txt。

marc.txt

column1 column2 .....  Family Subfamily 
.....   ......  .....    A     B
.....    .....  .....    A     B
.....    .....  ......   A     B

jaco.txt

column1 column2 .....  Family Subfamily 
.....   ......  .....    C     D
.....    .....  .....    C     D
.....    .....   ....    C     D

编辑:创建检查文件是否存在

像这样的东西应该可以工作:

df1 <- data.frame(Name = c("marc", "Jaco"),
                  Family = c("A.", "C"),
                  Subfamily = c("B", "D"))

files <- list.files(pattern = ".txt")
for (i in 1:nrow(df1)) {
  if (!paste0(df1[i,1], ".txt") %in% files) {
    next()
  }
  dfi <- read.csv(paste0(df1[i,1], ".txt"))
  dfi <- cbind(dfi, df1[i,-1])
  write.csv(dfi, paste0(df1[i,1], ".txt"))
}

只需要替换table个名字