假设我有以下数据框列表:
lst <- list(
a=data.frame(key=c(1,2,3), val=c(10,20,30)),
b=data.frame(key=c(1,2,3), val=c(100,200,300)),
c=data.frame(key=c(1,2,3), val=c(1000,2000,3000)),
d=data.frame(key=c(1,2), val=c(10000,20000)))
我如何创建一个 data.frame 如下? (或类似):
key val.a val.b val.c val.d
1 1 10 100 1000 10000
2 2 20 200 2000 20000
3 3 30 300 3000 NA
我试图这样做(但失败):
Browse[2]> Reduce(function(x,y) merge(x, y, by = 'key', all.x = T), lst)
key val.x val.y val.x val.y
1 1 10 100 1000 10000
2 2 20 200 2000 20000
3 3 30 300 3000 NA
Warning message:
In merge.data.frame(x, y, by = "key", all.x = T) :
column names ‘val.x’, ‘val.y’ are duplicated in the result
NOTE: I would prefer a base-R solution but am interested in other ways of doing this
最佳答案
我们可以使用 inner_join
与 reduce
之后 renaming
第二列与相应的 list
姓名
library(purrr)
library(dplyr)
library(stringr)
imap(lst, ~ { nm <- .y
.x %>%
rename_at(vars(val), ~ str_c(., ".", nm))}) %>%
reduce(full_join, by = 'key')
# key val.a val.b val.c val.d
#1 1 10 100 1000 10000
#2 2 20 200 2000 20000
#3 3 30 300 3000 30000
或在
base R
,我们使用 Map
对列进行重命名,然后在 OP 的帖子中,执行 merge
内Reduce
Reduce(function(...) merge(..., by = 'key', all = TRUE),
Map(function(x, y) setNames(x, c('key',
paste0(names(x)[-1], ".", y))), lst, names(lst)))
# key val.a val.b val.c val.d
#1 1 10 100 1000 10000
#2 2 20 200 2000 20000
#3 3 30 300 3000 30000
关于r - 如何从数据框列表中附加列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61256204/