使用 for 循环将来自 R 中不同子文件夹的多个文本文件绑定在一起
Use for loop to bind multiple text files together from different subfolders in R
我以前看过这个问题,但他们对解决我的问题没有多大帮助。
我希望绑定 (rbind
) 来自 150 个子文件夹的多个文本文件,但我只对每个文件夹中的 2 个不同文件感兴趣。详情如下:
- 名为 "Folder" 的主文件夹,其中包含 150 个子文件夹
- 在每个子文件夹中,我想提取以 1 和 11 开头的文件。(即 1_HDx1.txt 和 11_HDx1.txt)- 每个文件夹中有 2 个这样的文件
- 在数据框中创建一个列,其中包含从中提取文件的子文件夹的名称。
如果所有文件都在一个文件夹中,我知道如何执行此操作(直接见下文),但我可以对一个文件夹执行类似的操作吗??
z <- NULL
files <- dir("Folder")
for (file in files) {
x <- read.csv(file.path("Folder", file), as.is=TRUE)
x$source <- substring(file, 8, 10) #name of file for the source
z <- rbind(z, x)])
}
150 个中前 3 个子文件夹的文件结构:
Folder
- WSTNUM_001
- 1_HDx
- 2_LDx
- 3_LD
- 4_LD
- 5_ld
.....
- 11_Urbanx
- 12_Urbany
- WSTNUM_002
- 1_HDx
- 2_LDx
- 3_LD
- 4_LD
- 5_ld
.....
- 11_Urbanx
- 12_Urbany
- WSTNUM_003
- 1_HDx
- 2_LDx
- 3_LD
- 4_LD
- 5_ld
.....
- 11_Urbanx
- 12_Urbany`
我建议使用一系列 apply
函数。
假设您以文件夹完整目录作为工作目录开始:
Folders <- list.files() # creates a list of all the folders
# Looks in each folder and returns a path to all files starting with 1 or 11.
Paths <- lapply(Folders,function(x){
F <- list.files(x)
F <- F[grepl("^(1|11)",F)]
paste0(x,'/',F)
})
Paths <- unlist(Paths)
# Reads each of the selected files into a list.
Tables <- lapply(Paths, function(Path){
read.csv(Path, as.is=TRUE)
})
# Rbinds the list together
Data <- do.call(rbind,Tables)
我以前看过这个问题,但他们对解决我的问题没有多大帮助。
我希望绑定 (rbind
) 来自 150 个子文件夹的多个文本文件,但我只对每个文件夹中的 2 个不同文件感兴趣。详情如下:
- 名为 "Folder" 的主文件夹,其中包含 150 个子文件夹
- 在每个子文件夹中,我想提取以 1 和 11 开头的文件。(即 1_HDx1.txt 和 11_HDx1.txt)- 每个文件夹中有 2 个这样的文件
- 在数据框中创建一个列,其中包含从中提取文件的子文件夹的名称。
如果所有文件都在一个文件夹中,我知道如何执行此操作(直接见下文),但我可以对一个文件夹执行类似的操作吗??
z <- NULL
files <- dir("Folder")
for (file in files) {
x <- read.csv(file.path("Folder", file), as.is=TRUE)
x$source <- substring(file, 8, 10) #name of file for the source
z <- rbind(z, x)])
}
150 个中前 3 个子文件夹的文件结构:
Folder
- WSTNUM_001
- 1_HDx
- 2_LDx
- 3_LD
- 4_LD
- 5_ld
.....
- 11_Urbanx
- 12_Urbany
- WSTNUM_002
- 1_HDx
- 2_LDx
- 3_LD
- 4_LD
- 5_ld
.....
- 11_Urbanx
- 12_Urbany
- WSTNUM_003
- 1_HDx
- 2_LDx
- 3_LD
- 4_LD
- 5_ld
.....
- 11_Urbanx
- 12_Urbany`
我建议使用一系列 apply
函数。
假设您以文件夹完整目录作为工作目录开始:
Folders <- list.files() # creates a list of all the folders
# Looks in each folder and returns a path to all files starting with 1 or 11.
Paths <- lapply(Folders,function(x){
F <- list.files(x)
F <- F[grepl("^(1|11)",F)]
paste0(x,'/',F)
})
Paths <- unlist(Paths)
# Reads each of the selected files into a list.
Tables <- lapply(Paths, function(Path){
read.csv(Path, as.is=TRUE)
})
# Rbinds the list together
Data <- do.call(rbind,Tables)