R 循环遍历目录和文件,并将文件保存在具有不同名称的新目录中
我遇到了以下问题,到目前为止,我还没有找到一个合适的答案 我在以下目录的子文件夹中存储了大量数据集:R 循环遍历目录和文件,并将文件保存在具有不同名称的新目录中,r,loops,directory,subdirectory,R,Loops,Directory,Subdirectory,我遇到了以下问题,到目前为止,我还没有找到一个合适的答案 我在以下目录的子文件夹中存储了大量数据集: C:/Users/Desktop/Data Generation 子文件夹遵循以下模式: /Model 1/Model_1_250skew1mar1 模型可能从1变为3;以及250到750;倾斜1到3;3月1日至3日 例如:/Model 3/Model_3\u 750skew2mar2或/Model 2/Model_2\u 250skew3mar1 在这些子文件夹中,我得到了我的数据集:M
C:/Users/Desktop/Data Generation
子文件夹遵循以下模式:
/Model 1/Model_1_250skew1mar1
模型可能从1变为3;以及250到750;倾斜1到3;3月1日至3日
例如:/Model 3/Model_3\u 750skew2mar2或/Model 2/Model_2\u 250skew3mar1
在这些子文件夹中,我得到了我的数据集:M1_1
thruM1_1000
或者对于型号2M2_1
thruM2_1000
现在我想获取我的数据集:M1_1
thruM1_1000
,替换缺少的值,并根据获取数据集的位置将这些数据集保存在新目录中:
C:/Users/Desktop/Data Generation/ NA /Model 1/Model_1_250skew1mar1
我可以使用以下代码为我的一个子目录执行此操作:
files_M_neu <- list.files(path="C:/Users/Desktop/Data Generation/Model 1/Model_1_250skew1mar1",
pattern="M1_*[^list].dat", recursive=TRUE, full.names=TRUE)
dir.create("C:/Users/Desktop/Data Generation/NA")
dir.create("C:/Users/Desktop/Data Generation/NA/Model 1")
dir.create("C:/Users/Desktop/Data Generation/NA/Model 1/Model_1_250skew1mar1")
for(i in 1:length(files_M_neu)){
data <- read.table(files_M_neu[i], header=TRUE)
fix_missing <- function(x) {
x[x == 999] <- NA
x
}
data <- fix_missing(data)
write.table(data, paste("C:/Users/Desktop/Data Generation/NA/Model 1/Model_1_250skew1mar1/data[",i,"].dat"),
sep="\t", row.names = FALSE, col.names = FALSE)
rm(data)
}
files\u M\u neu这里有一个解决方案,它使用list.dirs()
递归读取wd下的所有目录,然后在wd/NA/下创建相同的目录树,最后使用dir()
或list.files()
和完整的相对名称来处理文件,并将它们保存在wd/NA/下的每个目录中:
# set wd to work with relative path ./
setwd("C:/Users/Desktop/Data Generation/")
# get the list of all directories:
dirList = NULL
for (d in list.dirs(path = ".", full.names=TRUE, recursive=TRUE)){
dirList = rbind(dirList, d)
}
# create the directories tree in ./NA/
for (d in dirList){
dir.create(paste0('NA',gsub("\\.", "", d)), recursive = TRUE)
}
# process files and save with full path to ./NA/
for (f in dir(path = ".", pattern = '*\\.dat$', full.names=TRUE, recursive=TRUE)){
data <- read.table(f, header=TRUE)
data <- fix_missing(data)
write.table(data, paste0('NA',gsub("\\./", "/", f)),
sep="\t", row.names = FALSE, col.names = FALSE)
rm(data)
}
#将wd设置为使用相对路径/
setwd(“C:/Users/Desktop/Data Generation/”)
#获取所有目录的列表:
dirList=NULL
对于(list.dirs(path=“.”,full.names=TRUE,recursive=TRUE)中的d){
dirList=rbind(dirList,d)
}
#在中创建目录树。/NA/
对于(目录中的d){
dir.create(paste0('NA',gsub('\\.','',d)),recursive=TRUE)
}
#处理文件并使用完整路径保存到。/NA/
对于(dir中的f(path=“.”,pattern='*\\.dat$',full.names=TRUE,recursive=TRUE)){
非常感谢!这对我帮助很大!!