简体   繁体   中英

Concatenate lists with same .names

I have lists v1 and v2 with the same names:

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") 

I want to concatenate the lists, while keeping the names, ie to get something like:

v12:  structure(list(ID = c("A1","B1"), Name = c("A2","B2"), 
.Names = c("ID", "Name")

Manual concatenation works:

v12<-cbind(Map(c, v1, v2))

But, if v1 and v2 are results of applying lapply(), and are stored in a list themselves, the similar logic does not seem to work:

v<-lapply(...)
v12<-cbind(Map(c,v))

What is the best way to automate the process? For example:

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))

results in:

ID  Name
A1  A2
B1  B2

not in:

  ID    Name
"A1","B1"   "A2","B2"

I find your question very unclear, but maybe you can try:

setNames(Reduce(function(x, y) paste(x, y, sep = ", "), v), 
         c("ID", "Name"))
#       ID     Name 
# "A1, B1" "A2, B2"

Or, add a t() in there too:

t(setNames(Reduce(function(x, y) paste(x, y, sep = ", "), v), 
           c("ID", "Name")))
     ID       Name    
[1,] "A1, B1" "A2, B2"

How about this?

> 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

An idea::

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

Second try:

unlist(apply(mapply(c,v), 1, function(x) list(unlist(x))), recursive = FALSE)
# output as list

Update: If you want to have unique values within each list, use this:

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)

If I understand correctly you want the a list with the same structure as the other two, but with the elements merged. In which case, try this:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM