我想合并来自不同文件夹的数据。因此,我首先使用当前工作目录中的所有地图名称(使用list.dirs())创建一个对象。之后,我会查看每个地图的特定文件名(我的模式)。 问题是当一个文件不包含这个特定的字符串时,list.files()会给出一个错误。list.files()可以忽略R中不包含模式的路径吗?
(Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'NA': No such file or directory).
当我只选择包含模式的地图时,代码就起作用了。
有没有人知道如何让list.files()忽略不包含特定模式的路径?
这是我的代码:
GS.dir<- list.dirs(path = ".", recursive = TRUE)
ligustrum <- c()
for (j in 1:length(GS.dir)){
files <- list.files(GS.dir[j], pattern = glob2rx("li*Avg.txt"), full.names = TRUE)
if(!is.null(files)){
for (i in 1:length(files)){
plot <- read.table(files[i], header = TRUE, sep = ",")
datum <- substr(files[i], 1, 8)
nummer <- substr(files[i], nchar(files[i]) - 7, nchar(files[i]) - 7)
plot.date <- data.frame("Date" = rep(datum, length(plot[,1])),
"plotnr"=rep(nummer,length(plot[,1])),
plot
)
ligustrum <- rbind(ligustrum, plot.date)
}
} else {
ligustrum <- ligustrum
}
}
write.table(ligustrum, "ligustrum.txt", sep = ";", row.names = FALSE)
你有没有调查在你的代码失败具体点吗?使用'for'循环,你可以运行它们,让它们失败,然后检查输入值是什么(在你的情况下'j'和'i')。通过这些输入,运行代码的每一步以查看它在哪里以及如何失败。 – rosscova
有两种方法可以处理“无字符串”,无论是为此测试还是使用if函数来避免或以某种方式处理它,或者使用tryCatch来捕获任何错误并处理它。通过这种方式,执行不会停止,并且该函数会继续运行。 –