r - 如何从文件夹中读取多个文件并更改 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代码吗?谢谢。
解决方案
所以我很确定有一种更优化的方法可以做到这一点,但我正在空白。如果我只是想把它搞定,我会做这样的事情:
#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()
}
推荐阅读
- apache-spark - Amazon EMR 上的 rdd.write.csv 时如何处理 S3 内部服务器错误?
- apache-spark - Apache Livy - 休息 API
- c++ - 识别链表中的节点是否为空
- spring - com.test.controller.TestController 中的字段 testService 需要找不到类型为“com.test.service.TestService”的 bean
- c - PSET 4 恢复分段故障 CS50
- docker - Docker 卷命名
- docusignapi - 调用 create_envelope api 给出 INVALID_USERID 错误
- flutter - 在 Flutter 中,如何在使用查询参数调用 showSearch() 后立即显示结果?
- c++ - 错误:无法开始调试。来自命令“-exec-run”的意外 GDB 输出。找不到进程 ID 1401 的 Mach 任务端口
- java - 线程池和连接池,需要帮助来理解它们是如何工作的 Java