在R中使用文件名进行循环 [英] For loop with file names in R
问题描述
我有一个文件列表,如:
I have a list of files like:
nE_pT_sbj01_e2_2.csv
,
nE_pT_sbj02_e2_2.csv
,
nE_pT_sbj04_e2_2.csv
,
nE_pT_sbj05_e2_2.csv
,
nE_pT_sbj09_e2_2.csv
,
nE_pT_sbj10_e2_2.csv
nE_pT_sbj01_e2_2.csv
,
nE_pT_sbj02_e2_2.csv
,
nE_pT_sbj04_e2_2.csv
,
nE_pT_sbj05_e2_2.csv
,
nE_pT_sbj09_e2_2.csv
,
nE_pT_sbj10_e2_2.csv
如您所见,文件名是相同的,但'sbj'(主题编号)不是连续的.
As you can see, the name of the files is the same with the exception of 'sbj' (the number of the subject) which is not consecutive.
我需要运行一个for循环,但我想保留该主题的原始编号.这该怎么做?
我认为我需要用保留主题原始编号的内容替换length(file)
,但不确定如何执行.
I need to run a for loop, but I would like to retain the original number of the subject. How to do this?
I assume I need to replace length(file)
with something that keeps the original number of the subject, but not sure how to do it.
setwd("/path")
file = list.files(pattern="\\.csv$")
for(i in 1:length(file)){
data=read.table(file[i],header=TRUE,sep=",",row.names=NULL)
source("functionE.R")
Output = paste("e_sbj", i, "_e2.Rdata")
save.image(Output)
}
上面的代码为我提供了输出:
The code above gives me as output:
e_sbj1_e2.Rdata
,e_sbj2_e2.Rdata
,e_sbj3_e2.Rdata
,
e_sbj4_e2.Rdata
,e_sbj5_e2.Rdata
,e_sbj6_e2.Rdata
.
相反,我想获得:
e_sbj01_e2.Rdata
,e_sbj02_e2.Rdata
,e_sbj04_e2.Rdata
,
e_sbj05_e2.Rdata
,e_sbj09_e2.Rdata
,e_sbj10_e2.Rdata
.
推荐答案
删除扩展名"csv",然后添加"Rdata",并在循环中使用文件名,例如:
Drop the extension "csv", then add "Rdata", and use filenames in the loop, for example:
myFiles <- list.files(pattern = "\\.csv$")
for(i in myFiles){
myDf <- read.csv(i)
outputFile <- paste0(tools::file_path_sans_ext(i), ".Rdata")
outputFile <- gsub("nE_pT_", "e_", outputFile, fixed = TRUE)
save(myDf, file = outputFile)
}
注意:我更改了您的变量名,请尽量避免将函数名用作变量名.
Note: I changed your variable names, try to avoid using function names as a variable name.
这篇关于在R中使用文件名进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!