【发布时间】:2020-07-08 13:32:08
【问题描述】:
首先,如果这个问题已经在其他地方得到解决但我找不到答案,我们深表歉意。
在R 中,我有一个for loop,它根据特定条件将文本(writeLines)保存到文件中。我想将每 10 个写入的文件保存到一个新的不同子文件夹中。这样每个子文件夹最多只能有10个文件。
现在,如果要写入所有文件,我可以编写一个脚本来执行此操作(见下文),但我不确定每次文件夹已满 10 个文件时如何实现子文件夹的更改。
下面的例子应该澄清一下。
# generate random num
set.seed(15)
input <- rnorm(100, mean = 10, sd = 3)
# Write to file only if num is greater than threshold
thrshld <- 10
out_dir <- "~/R/tmp/Batch_Saving"
k <- 1
i <- 1
for (i in 1:length(input)) {
if ( any(i == seq(from = 1, to = length(input), by = 10) ) ) {
# Create a new subfolder everytime i is a multiple of 10
sub_dir <- paste0(out_dir, "/Dir_Num_", k)
k <- k+1
}
if ( input[i] > thrshld) {
txt <- paste("The number", signif(input[i], 4), "is greater than", thrshld)
# Create folder if it doesn't exist
if (!dir.exists(sub_dir)) { dir.create(sub_dir, recursive = T) }
# Write text to file
writeLines(text = txt,
con = paste0(sub_dir, "/file_", i, ".txt") )
}
}
此脚本创建 10 个文件夹,每个文件夹少于 10 个文件,但文件数量不同。可以像这样在终端中快速检查:
Batch_Saving > find . -maxdepth 1 -mindepth 1 -type d -exec sh -c 'echo "{} : $(find "{}" -type f | wc -l)" file\(s\)' \;
./Dir_Num_4 : 6 file(s)
./Dir_Num_3 : 7 file(s)
./Dir_Num_2 : 4 file(s)
./Dir_Num_5 : 7 file(s)
./Dir_Num_10 : 4 file(s)
./Dir_Num_9 : 5 file(s)
./Dir_Num_7 : 3 file(s)
./Dir_Num_6 : 6 file(s)
./Dir_Num_1 : 6 file(s)
./Dir_Num_8 : 4 file(s)
我相信实现这一点的唯一方法是每次读取已经写入了多少文件,或者以某种方式跟踪已经写入了多少文件并相应地更改参数k。
我相信这也可以通过其他方法(即apply)实现,但为了学习,我想在循环中编写代码。
非常感谢!
【问题讨论】:
标签: r for-loop if-statement indexing write.table