如何合并列表中包含的不同大小的数据aframes的元素[R]?

时间:2021-11-14 22:57:39

I have a list composed by 5 data.frames of different sizes, each data.frame has two variables, Group.1 and x, i would like to merge those data.frames by the Group.1 variables. Of course I expect NA values to be generated.

我有一个由5个不同大小的数据组成的列表,每个数据。frame有两个变量,Group.1和x,我想要合并这些数据。当然,我希望生成NA值。

Example:

例子:

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"))

An extra note: I would like to use apply (or lapply) to test it with different list sizes.

注意:我想使用apply(或lapply)测试不同列表大小的列表。

Many thanks!

很多谢谢!

1 个解决方案

#1


3  

Reduce() works nicely with merge() on a list.

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

#1


3  

Reduce() works nicely with merge() on a list.

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