我正在使用R通过应用程序处理文件。该应用程序需要一个简单的输入文件,输出文件名规范作为参数。使用以下代码,可以正常工作。
input <- "\"7374.txt\""
output <- "\"7374_cleaned.txt\""
system2("DataCleaner", args = c(input, output))
但是,我希望处理一个.txt文件文件夹,而不是分别处理每个。如果我可以访问源代码,则只需更改应用程序即可接受文件夹,而不是单个文件,但不幸的是我没有。有可能以某种方式在R中执行此操作吗?我曾尝试开始创建一个循环,
input <- dir(pattern=".txt")
但是我不知道如何在不包含正则表达式的情况下将向量作为参数插入?另外我还需要能够将'_cleaned'粘贴到输出文件名的末尾?提前谢谢了。
显然,我无法测试它,因为我没有您的DataCleaner
程序,但是呢...
# make some files
dir.create('folder')
x = sapply(seq_along(1:5), function(f) {t = tempfile(tmpdir = 'folder', fileext = '.txt'); file.create(t); t})
# find the files
inputfiles = list.files(path = 'folder', pattern = 'txt', full.names = T)
# remove the extension
base = tools::file_path_sans_ext(inputfiles)
# make the output file names
outputfiles = paste0(base, '_cleaned.txt')
mysystem <- function(input, output) {
system2('DataCleaner', args = c(input, output))
}
lapply(seq_along(1:length(inputfiles)), function(f) mysystem(inputfiles[f], outputfiles[f]))
它用于lapply
遍历输入和输出文件的所有成员,并调用system2函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句