连接具有相同.name的列表 [英] Concatenate lists with same .names

查看:65
本文介绍了连接具有相同.name的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有名称相同的列表v1和v2:

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, i.e. to get something like:

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

手动串联工作:

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

但是,如果v1和v2是应用lapply()的结果,并且自身存储在列表中,则类似的逻辑似乎不起作用:

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

导致:

ID  Name
A1  A2
B1  B2

不在:

  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"

或者在其中添加t():

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

这篇关于连接具有相同.name的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆