【发布时间】:2018-06-15 13:02:09
【问题描述】:
我有一个目录,其中有多个站点和年份的多个文件,具有完全相同的内部结构。我想合并(rbind)来自同一站点的每个文件。 这是适用于一个站点的代码(在“模式”中定义),但我不想为每个站点名称手动执行此操作,而是想创建一个为所有站点执行此操作的循环。
ls1 <- list.files(path = dossier, pattern = "CH", all.files = FALSE,
full.names = FALSE, recursive = FALSE,
ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
ld1 <- lapply(ls1, function(x) read.csv(file=file.path(dossier,x), sep=",", header=T, stringsAsFactors=FALSE))
tot1 <- do.call("rbind", ld1)
write.table(tot1, file=file.path(dossier,"CH-Oe1_2002-2006.csv"),col.names=TRUE, row.names=FALSE, sep=";")
ls2 <- list.files(path = dossier, pattern = "FR-Fon", all.files = FALSE,
full.names = FALSE, recursive = FALSE,
ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
ld2 <- lapply(ls2, function(x) read.csv(file=file.path(dossier,x), sep=",", header=T, stringsAsFactors=FALSE))
tot2 <- do.call("rbind", ld2)
write.table(tot2, file=file.path(dossier,"FR-Fon_2002-2006.csv"),col.names=TRUE, row.names=FALSE, sep=";")
ls3 <- list.files(path = dossier, pattern = "FR-Gri", all.files = FALSE,
full.names = FALSE, recursive = FALSE,
ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
ld3 <- lapply(ls3, function(x) read.csv(file=file.path(dossier,x), sep=",", header=T, stringsAsFactors=FALSE))
tot3 <- do.call("rbind", ld3)
write.table(tot3, file=file.path(dossier,"FR-Gri_2002-2006.csv"),col.names=TRUE, row.names=FALSE, sep=";")
ls4 <- list.files(path = dossier, pattern = "FR-Lq2", all.files = FALSE,
full.names = FALSE, recursive = FALSE,
ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
ld4 <- lapply(ls4, function(x) read.csv(file=file.path(dossier,x), sep=",", header=T, stringsAsFactors=FALSE))
tot4 <- do.call("rbind", ld4)
write.table(tot4, file=file.path(dossier,"FR-Lq2_2002-2006.csv"),col.names=TRUE, row.names=FALSE, sep=";")
所以,这里的变化是:“模式”中的名称和要保存在 write.table 中的名称。
有什么想法可以简化这个吗? 非常感谢提前
【问题讨论】:
-
例如,只需将您的模式名称放在一个向量中,然后使用
lapply循环遍历它们。