如何合并列表中包含的不同大小的数据帧的元素[R]?
How to merge elements of dataframes of different sizes containded in a list [R]?
我有一个由 5 个不同大小的 data.frames
组成的列表,每个 data.frame
有两个变量,Group.1
和 x
,我想合并那些 data.frames 通过 Group.1
变量。当然,我希望生成 NA
个值。
示例:
Group.1 = c(01, 03, 05)
x = c(2000, 4000, 5000)
a <- data.frame(Group.1, x)
Group.1 = c(03, 05)
x = c(400, 500)
b <- data.frame(Group.1, x)
Group.1 = c(01, 05)
x = c(2000,2500)
c <- data.frame(Group.1, x)
lst <- list(a,b,c)
variables <- as.numeric(c(1:3))
test2 <- lapply(variables, function(t) merge((data.frame(lst[t])), by="Group.1"))
额外说明:我想使用 apply(或 lapply)来测试不同的列表大小。
非常感谢!
Reduce()
与列表中的 merge()
配合得很好。
Reduce(function(...) merge(..., by = "Group.1", all = TRUE), lst)
# Group.1 x.x x.y x
# 1 1 2000 NA 2000
# 2 3 4000 400 NA
# 3 5 5000 500 2500
我有一个由 5 个不同大小的 data.frames
组成的列表,每个 data.frame
有两个变量,Group.1
和 x
,我想合并那些 data.frames 通过 Group.1
变量。当然,我希望生成 NA
个值。
示例:
Group.1 = c(01, 03, 05)
x = c(2000, 4000, 5000)
a <- data.frame(Group.1, x)
Group.1 = c(03, 05)
x = c(400, 500)
b <- data.frame(Group.1, x)
Group.1 = c(01, 05)
x = c(2000,2500)
c <- data.frame(Group.1, x)
lst <- list(a,b,c)
variables <- as.numeric(c(1:3))
test2 <- lapply(variables, function(t) merge((data.frame(lst[t])), by="Group.1"))
额外说明:我想使用 apply(或 lapply)来测试不同的列表大小。
非常感谢!
Reduce()
与列表中的 merge()
配合得很好。
Reduce(function(...) merge(..., by = "Group.1", all = TRUE), lst)
# Group.1 x.x x.y x
# 1 1 2000 NA 2000
# 2 3 4000 400 NA
# 3 5 5000 500 2500