我有一个看起来像这样的列表
[[1]]
users V1
1 28 3
2 33 1
3 35 4
4 260 1
[[2]]
users V1
1 33 2
2 260 1
3 285 13
如何使用R创建像这样的表?
users V1 V2
1 28 3 NA
2 33 1 2
3 35 4 NA
4 260 NA 1
5 285 13 NA
答案 0 :(得分:2)
你可以尝试
Reduce(function(...) merge(..., by='users', all=TRUE), lst)
# users V1.x V1.y
#1 28 3 NA
#2 33 1 2
#3 35 4 NA
#4 260 1 1
#5 285 NA 13
另一种选择是使用join_all
中的plyr
。但是,这要求除by=
中使用的列名称之外的列名称不同。
library(plyr)
nm1 <- make.names(sapply(lst, colnames)[-1,],unique=TRUE)
join_all(Map(function(x,y) {names(x)[-1] <- y; x}, lst, nm1),
by='users', type='full')
# users V1 V1.1
#1 28 3 NA
#2 33 1 2
#3 35 4 NA
#4 260 1 1
#5 285 NA 13
lst <- list(structure(list(users = c(28L, 33L, 35L, 260L), V1 = c(3L,
1L, 4L, 1L)), .Names = c("users", "V1"), class = "data.frame",
row.names = c("1", "2", "3", "4")), structure(list(users = c(33L, 260L, 285L),
V1 = c(2L, 1L, 13L)), .Names = c("users", "V1"), class = "data.frame",
row.names = c("1", "2", "3")))
答案 1 :(得分:1)
您可以在列表中使用do.call
merge
。
l <- list(structure(list(users = c(28, 33, 35, 260), V1 = c(3, 1,
4, 1)), .Names = c("users", "V1"), row.names = c(NA, -4L), class = "data.frame"),
structure(list(users = c(33, 260, 285), V1 = c(2, 1, 13)), .Names = c("users",
"V1"), row.names = c(NA, -3L), class = "data.frame"))
do.call(merge, c(l, list(all = TRUE, by = "users")))
# users V1.x V1.y
#1 28 3 NA
#2 33 1 2
#3 35 4 NA
#4 260 1 1
#5 285 NA 13