我列出了名称相同的v1和v2:
v1: structure(list(ID = c("A1"), Name = c("A2"),.Names = c("ID", "Name")
...
v2: structure(list(ID = c("B1"), Name = c("B2"),.Names = c("ID", "Name")
我希望连接列表,同时保留名称,即得到类似的内容:
v12: structure(list(ID = c("A1","B1"), Name = c("A2","B2"),
.Names = c("ID", "Name")
手动连接工作:
v12<-cbind(Map(c, v1, v2))
但是,如果v1和v2是应用lapply()的结果,并且本身存储在列表中,则类似的逻辑似乎不起作用:
v<-lapply(...)
v12<-cbind(Map(c,v))
自动化流程的最佳方法是什么?例如:
v1 <- structure(list(ID = c("A1"), Name = c("A2")),.Names = c("ID", "Name"))
v2 <- structure(list(ID = c("B1"), Name = c("B2")),.Names = c("ID", "Name"))
v <- list(v1, v2)
k<-t(mapply(c, v))
结果:
ID Name
A1 A2
B1 B2
不在:
ID Name
"A1","B1" "A2","B2"
答案 0 :(得分:1)
我发现您的问题非常不清楚,但也许您可以尝试:
setNames(Reduce(function(x, y) paste(x, y, sep = ", "), v),
c("ID", "Name"))
# ID Name
# "A1, B1" "A2, B2"
或者,也在其中添加t()
:
t(setNames(Reduce(function(x, y) paste(x, y, sep = ", "), v),
c("ID", "Name")))
ID Name
[1,] "A1, B1" "A2, B2"
答案 1 :(得分:1)
这个怎么样?
> data.frame(ID = do.call("paste", c(lapply(v, FUN = "[", "ID"), sep = ",")),
+ Name = do.call("paste", c(lapply(v, FUN = "[", "Name"), sep = ",")))
ID Name
1 A1,B1 A2,B2
答案 2 :(得分:0)
一个想法::
v1 <- structure(list(ID = c("A1"), Name = c("A2")),.Names = c("ID", "Name"))
v2 <- structure(list(ID = c("B1"), Name = c("B2")),.Names = c("ID", "Name"))
v <- list(v1, v2)
t(mapply(c, v)) # output as matrix
第二次尝试:
unlist(apply(mapply(c,v), 1, function(x) list(unlist(x))), recursive = FALSE)
# output as list
更新:如果您想在每个列表中包含唯一值,请使用以下命令:
v3 <- list(ID = "B1", Name = "B3")
vx <- list(v1, v2, v3)
unlist(apply(mapply(c,vx), 1,
function(x) list(unique(unlist(x)))), recursive = FALSE)
答案 3 :(得分:0)
如果我理解正确,你想要一个与其他两个结构相同的列表,但是要合并元素。在这种情况下,试试这个:
ul <- unlist(list(v1,v2))
sapply(unique(names(ul)),function(x) as.vector(ul[names(ul)%in%x]),simplify=FALSE)
$ID
[1] "A1" "B1"
$Name
[1] "A2" "B2"