我有一个列表,mylist
包含5个元素。
我可以使用以下内容合并任何两个元素:
merge(mylist[[1]], mylist[[2]], by = someColumn).
但是,如何在保留名称而不引起警告的情况下一次合并所有这些内容。
谢谢!
修改
经过进一步检查,这里有一些细节可以帮助澄清我的问题:
> mylist
$Alpha
id count
1 ABC 5
2 DEF 10
3 GHI 15
$Beta
id count
1 DEF 10
2 ABC 12
3 GHI 14
$Gamma
id count
1 ABC 13
2 GHI 15
3 DEF 17
$Kappa
id count
1 GHI 20
2 DEF 21
3 ABC 25
> Reduce(function(x,y){merge(x,y,by="id")}, mylist)
id count.x count.y count.x count.y
1 ABC 5 12 13 25
2 DEF 10 10 17 21
3 GHI 15 14 15 20
Warning message:
In merge.data.frame(x, y, by = "id") :
column names ‘count.x’, ‘count.y’ are duplicated in the result
如您所见,事情在结果的顶部重复,R会发出警告。我怎样才能避免这种情况(最好用列表名称调用列名 - 所以第一个count.x将是count.Alpha)。
如果有人想要,请点击这里的mylist
副本:
structure(list(Alpha = structure(list(id = structure(1:3, .Label = c("ABC",
"DEF", "GHI"), class = "factor"), count = c(5, 10, 15)), .Names = c("id",
"count"), row.names = c(NA, -3L), class = "data.frame"), Beta = structure(list(
id = structure(c(2L, 1L, 3L), .Label = c("ABC", "DEF", "GHI"
), class = "factor"), count = c(10, 12, 14)), .Names = c("id",
"count"), row.names = c(NA, -3L), class = "data.frame"), Gamma = structure(list(
id = structure(c(1L, 3L, 2L), .Label = c("ABC", "DEF", "GHI"
), class = "factor"), count = c(13, 15, 17)), .Names = c("id",
"count"), class = "data.frame", row.names = c(NA, -3L)), Kappa = structure(list(
id = c("GHI", "DEF", "ABC"), count = c(20, 21, 25)), .Names = c("id",
"count"), row.names = c(NA, -3L), class = "data.frame")), .Names = c("Alpha",
"Beta", "Gamma", "Kappa"))
答案 0 :(得分:4)
您可以快速Map
重命名"计数"柱。例如
Reduce(merge, Map(function(n,x) {names(x)[2]<-n; x}, names(mylist), mylist))
返回
id Alpha Beta Gamma Kappa
1 ABC 5 12 13 25
2 DEF 10 10 17 21
3 GHI 15 14 15 20
答案 1 :(得分:0)
使用match.call()
的另一种方式:
Reduce(merge, lapply(mylist, function(x) {
names(x)[2] <- paste(names(x)[2], names(mylist)[match.call()[[2]][[3]]],sep=".")
x}))
# id count.Alpha count.Beta count.Gamma count.Kappa
#1 ABC 5 12 13 25
#2 DEF 10 10 17 21
#3 GHI 15 14 15 20