【问题标题】:Reading .tsv files from different folders into R environment and adding a column with the folder name将不同文件夹中的 .tsv 文件读取到 R 环境中并添加具有文件夹名称的列
【发布时间】:2018-10-31 10:59:16
【问题描述】:

我正在尝试将一系列 .tsv 输出文件读入 R 环境到同一个数据帧中。但是,每个输出文件位于不同的子文件夹中,但名称相同。

Folder1 中的 file.tsv 示例

  A B   C
  1 1   40
  2 1   45

示例路径:

A:/output/Folder1/file.tsv

A:/output/Folder2/file.tsv

A:/output/Folder3/file.tsv

文件夹名称包含重要信息,我想将其保存在聚合数据框中。

例子:

  A B   C   folder 
  1 1   40  Folder1 
  2 1   45  Folder1 
  3 1   50  Folder2
  4 1   55  Folder2
  5 1   60  Folder3
  6 1   65  Folder3

我找到了允许您从不同文件夹 (Read several files in different directories in r) 读入和附加 .tsv 文件的答案,但我在如何添加具有 文件夹 名称的列上遇到问题。我有 395 个独特的文件夹,所以我只想在万不得已的情况下手工制作列。

感谢您提供的任何见解!

【问题讨论】:

    标签: r csv


    【解决方案1】:

    改编自我的answer here。您需要以下步骤:

    # load the needed packages
    library(dplyr)
    
    # create a list of the filenames with the full path
    file.list <- list.files(pattern='*.tsv', recursive = TRUE, full.names = TRUE)
    
    # read the files into a list
    # using 'simplify=FALSE' makes sure the full paths are used as names in the list
    df.list <- sapply(file.list, read.delim, simplify=FALSE)
    
    # bind the dataframes in the list together with 'bind_rows' from the dplyr-package
    # use to replace the full path name with the folder name
    df <- bind_rows(df.list, .id = "folder") %>%
      mutate(folder = sub('.*/(.*)/.*$', '\\1', folder))
    

    【讨论】:

    • 非常感谢您的帮助!我必须对此进行的唯一更改是表示文件是制表符分隔的,而不是我这样做的逗号分隔,`df.list
    • @Charlotte 确实有效。我看到我忘记将read.csv 更改为read.delim(默认为sep = "\t")。
    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 2020-01-13
    • 2017-11-29
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多