[英]R read files with for loop
I just want to use use 10 files in R.我只想在 R 中使用 10 个文件。 For each I want to calculate something.
对于每个我想计算的东西。 Exp.
经验。 file: stat1_pwg1.out stat23_pwg2.out.. stat45_pwg10.out
文件:stat1_pwg1.out stat23_pwg2.out.. stat45_pwg10.out
I try this:我试试这个:
for (i in 1:10){
Data=paste("../XYZ/*_pwg",i,".out",sep="")
line=read.table(Data,head=T)
}
But it does not work?但它不起作用? Any hinds?
有后遗症吗?
I suspect your problem comes from the wildcard *
.我怀疑您的问题来自通配符
*
。 A better way to do this might be to first store the file names using dir
, then find the ones you want.一个更好的方法可能是首先使用
dir
存储文件名,然后找到你想要的。
files <- dir("../XYZ",pattern="stat[0-9]+_pwg[0-9]+\.out")
for(f in files) {
line=read.table(Data,head=T)
}
You could also use one of the apply
family of functions to eliminate the for loop entirely.您还可以使用
apply
系列函数之一来完全消除 for 循环。
A few things about your code.关于你的代码的一些事情。
paste
is vectorised, so you can take it out of the loop. paste
是矢量化的,因此您可以将其从循环中取出。
paste("../XYZ/*_pwg", 1:10, ".out", sep = "")
(Though as you'll see in a moment, you don't actually need to use paste
at all.) (尽管您稍后会看到,实际上根本不需要使用
paste
。)
read.table
won't accept wildcards; read.table
不接受通配符; it needs an exact match on the file name.它需要与文件名完全匹配。
Rather than trying to construct a vector of the filenames, you might be better using dir
to find the files that exist in your directory, filtered by a suitable naming scheme.与其尝试构建文件名的向量,不如使用
dir
来查找目录中存在的文件,并通过合适的命名方案进行过滤。
To filter the files, you use a regular expression in the pattern argument.要过滤文件,请在模式参数中使用正则表达式。 You can convert from wildcards to regular expression using
glob2rx
.您可以使用
glob2rx
从通配符转换为正则表达式。
file_names <- dir("../XYZ", pattern = glob2rx("stat*_pwg*.out"))
data_list <- lapply(filenames, read.table, header = TRUE)
For a slightly more specific fit, where the wildcard only matches numbers than anything, you need to use regular expressions directly.对于更具体的匹配,通配符只匹配数字而不是任何东西,您需要直接使用正则表达式。
file_names <- dir("../XYZ", pattern = "^stat[[:digit:]]+_pwg[[:digit:]]+\\.out$")
files <- dir(pattern="*Rip1_*")
files
for (F in files){ assign(F , Readfunc(F))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.