【发布时间】:2016-11-23 08:41:59
【问题描述】:
我想合并来自不同文件夹的数据。因此,我首先在当前工作目录中创建一个包含所有地图名称的对象(使用 list.dirs())。之后,我在每张地图中查找特定文件名(我的模式)。 问题是当文件不包含此特定字符串时, list.files() 会出错。
(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)。使用这些输入,运行代码的每个步骤以查看失败的位置和方式。 -
有两种方法可以处理“无字符串”,或者对此进行测试并使用
if函数以某种方式避免或处理它,或者使用tryCatch捕获任何错误并处理它.这样执行就不会停止,函数会运行得更远。
标签: r