我在列表中有多个文件,我想根据Year
列合并它们,以便我的新文件
看起来像Merged_file
。如果我有2个文件,我可以使用merge(file1, file2, by="Year")
,但我不知道如何为列表中的多个文件执行此操作。
我也试过newlist <- lapply(files, function(t)do.call(rbind.fill, t))
,但这不是我想要的。
file1 file2 Merged_file
Year Value1 Year Value2 Year Value1 Value2
2001 1 2000 0.5 2001 1 0.3
2001 2 2000 0.6 2001 2 0.3
2002 2 2001 0.3 2002 2 0.5
2002 3 2001 0.3 2002 3 0.6
2003 3 2002 0.5 2003 3 0.6
2003 4 2002 0.6 2003 4 0.6
2003 0.6
2003 0.6
答案 0 :(得分:1)
您说每个数据集中的行数不同;但是,任何一年都有相同的行数吗?我觉得你想要在同一年获取文件的子集并组合(cbind
)它们,但我不确定。看看这是否符合您的要求/意思:
file1 <- read.table(text=
"Year Value1
2001 1
2001 2
2002 2
2002 3
2003 3
2003 4", header=TRUE)
file2 <- read.table(text=
"Year Value2
2000 0.5
2000 0.6
2001 0.3
2001 0.3
2002 0.5
2002 0.6
2003 0.6
2003 0.6", header=TRUE)
bind.by.var <- function(file1, file2, var = intersect(names(file1), names(file2))) {
do.call(rbind, lapply(intersect(file1[[var]], file2[[var]]), function(y) {
cbind(file1[file1[[var]]==y,],
file2[file2[[var]]==y,setdiff(names(file2),var),drop=FALSE])
}))
}
函数bind.by.var
确定两个文件共有哪一列(Year),然后在两个文件中显示哪些年份。然后,逐年将这些年份结合在一起。我不知道这是否符合您的要求,但它确实符合您的Merged_file
示例
> bind.by.var(file1, file2)
Year Value1 Value2
1 2001 1 0.3
2 2001 2 0.3
3 2002 2 0.5
4 2002 3 0.6
5 2003 3 0.6
6 2003 4 0.6
鉴于此和文件列表,您可以使用Reduce
技术。
Reduce(bind.by.var, list(file1, file2))
将显式列表替换为从文件中读入的data.frame列表。
这里假设每个文件中任何一年的行数都相同。如果不是这种情况,您需要解释如何组合/合并一年中的数据。
答案 1 :(得分:0)
考虑使用“plyr”包,命令为“ldply”。
### Create a vector of file names to be read in
files <- list.files()
### Iterate over each file, reading in data each time
data <- lapply(files, read.csv)
### Use "ldply" to merge files from a list into a data.frame
data <- ldply(data)