【问题标题】:Match files names in a directory with names in a dataframe column - Paste matched row as columns in the matched file将目录中的文件名称与数据框列中的名称匹配 - 将匹配的行粘贴为匹配文件中的列
【发布时间】:2021-11-10 08:33:19
【问题描述】:

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

这些 filenames.txt 以相同的方式写入 R 数据帧的 column1 行。

files.txt 小于数据框 column1 行!这意味着不是 column1 的所有行都会匹配!

我想做什么:

如果文件名与 column1 名称匹配,则在同一行(R 数据框)插入第 2 列和第 3 列的名称,这作为 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

【问题讨论】:

    标签: r directory string-matching


    【解决方案1】:

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

    这样的事情应该可以工作:

    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"))
    }
    

    只需要替换表名

    【讨论】:

    • 感谢您的帮助!问题是它搜索匹配列表中的名字,但数据框的名字不在文件之间。我需要一个命令说只对目录中确实找到的文件执行此工作。这并不意味着数据帧的第 1 列的所有名称都将匹配。错误:文件中的错误(文件,“rt”):无法打开连接另外:警告消息:在文件(文件,“rt”)中:无法打开文件'filename1.txt':没有这样的文件或目录@Wietse de弗里斯
    • @Myke 创建了一个检查,检查每个迭代是否存在文件,如果不存在,代码将跳到下一个i
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多