首页 > 解决方案 > 如何从文件夹中读取多个文件并更改 r 中的列名

问题描述

我在一个目录下有几个文件夹,每个文件夹都有一个与文件夹同名的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代码吗?谢谢。

标签: rdirectoryreadfile

解决方案


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

#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()
}

推荐阅读