在R中使用循环来输出许多文件 [英] using a loop in R to output many files
问题描述
我的目标是通过循环功能运行名为"myname.output/"的文件夹中的所有文件,以生成多个CSV文件,每个文件均为myname1,myname2 ...等.
My goal it to run all the files in a folder called "myname.output/" through a loop function to generate multiple CSV files each being myname1, myname2 .... etc
这是我到目前为止所拥有的
This is what i have so far
sample_d <- list.dirs("myname.output/", recursive = F)
batch_process_samples <- function (sample_d) {
for (file in list.dirs("sample_d", full.names = T)) {
writef <- process_s(file)
write.csv(writef "myname.csv")
}
}
process_s是另一个文件中的函数.
Where process_s is a function in a different file.
然而它不起作用......我很确定我可以使用sprintf创建唯一的文件名,但是我不确定如何,谢谢!
However it does not work... I am pretty sure i can use sprintf to create unique file names but I'm not exactly sure how, Thanks!
更多信息:如果我运行它给变量的赋值,则该函数起作用,只是变量出来为空,但没有R错误.
Just more info: if i run it an assign to to a variable, the function works just the variable comes out empty, but no R errors.
推荐答案
您可以使用粘贴创建唯一的文件名.这对我有用:
You can create unique file names using paste. This worked for me:
sample_d <- list.files("myname.output/", recursive=F)
i <- 0
batch_process_samples <- function(file_list) {
for(file in file_list) {
i++
writef <- data.frame(read.csv(file))
write.csv(writef, file = paste0("myname",i,".csv"))
}
}
batch_process_samples(sample_d)
如果您正在读取文件,则需要 list.files()
而不是 list.dirs()
.
If you're reading files, you'll want list.files()
instead of list.dirs()
.
这篇关于在R中使用循环来输出许多文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!