【问题标题】:How to read several files from folders and change the column name in r如何从文件夹中读取多个文件并更改 r 中的列名
【发布时间】:2020-11-03 19:14:40
【问题描述】:

我在一个目录下有几个文件夹,每个文件夹都有一个与文件夹同名的txt文件。例如,主目录是 XYZ,在其下,我有 400 个文件夹,如 A01B、A22C、A12D...Z45F,在这些文件夹中,文件如 A01B.txt、A22C.txt、A12D.txt...Z45F。文本。此外,所有这些 txt 文件都有 2 列(所有 txt 文件的长度相同,6000 行),所有 txt 文件的第一列都相同。现在,我想要将所有这些文件读入一个数据框中,第二列命名为文件名,第一列命名为 ID。

read.table(XYZ/A01B/A01B.txt) 会给出一个类似的表格

AA00001    1.5
AA00002    2.3
AA00003    0.5
AA00004    4.8

read.table(XYZ/A22C/A22C.txt) 会给出一个类似的表格

AA00001    8.6
AA00002    6.1
AA00003    9.5
AA00004    1.1

我想要一张这样的桌子

ID         A01B  A22C
AA00001    1.5   8.6
AA00002    2.3   6.1
AA00003    0.5   9.5
AA00004    4.8   1.1

你能帮我写一下 R 代码吗?谢谢。

【问题讨论】:

    标签: r directory readfile


    【解决方案1】:

    所以我很确定有一种更优化的方法可以做到这一点,但我正在空白。但是,如果我只是想解决这个问题,我会做这样的事情:

    #tidyverse has all the things I want and more
    library(tidyverse)
    
    #this lists all the files in your directory so you don't have to hand jam them
    files_list <- list.files(path = "XYZ",recursive = T,full.names = T)
    
    #here, I make a custom function that reads the table and assigns it new column names
    read_custom <- function(directory) {
      df <- read.table(directory)
      colnames(df) <- c("ID",str_extract(directory,"\\w+(?=\\.txt"))
      return(df)
    }
    
    #do the first one and make a new dataframe
    df1 <- read_custom(files_list[1])
    
    #start a progress bar (trust me you want to do these on loops that might take a while)
    p <- progress_estimated(length(files_list) - 1)
    
    for(i in 2:length(files_list)) {
      #use our fancy custom reading function to make a temporary data frame
      temp <- read_custom(files_list[i])
    
      #join it to the old one
      df1 <-  full_join(df1,temp)
      
      #tick the progress bar and print it (seriously, this is so helpful to keep you from going crazy)
      p$tick()$print()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 2016-06-14
      • 2019-02-17
      • 1970-01-01
      • 2017-01-26
      • 2020-03-31
      • 1970-01-01
      • 2018-01-27
      相关资源
      最近更新 更多