0

我有同名的列表 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"
4

4 回答 4

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
于 2012-10-03T08:05:10.617 回答
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"
于 2012-10-03T07:28:04.987 回答
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"
于 2012-10-03T08:22:13.730 回答
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)
于 2012-10-03T07:26:41.200 回答