[R] Merge list element by name

David Winsemius dwinsemius at comcast.net
Fri Apr 14 00:13:21 CEST 2017


> On Apr 13, 2017, at 7:56 AM, Mohammad Tanvir Ahamed via R-help <r-help at r-project.org> wrote:
> 
> Hi, 
> I have a list like 
> kk<- list (a = 1:5, b = 6:10, c = 4:11)
> 
> Now i want to merger (Union) the list element "a" and "c" by name .
> 
> My expected outcome is 
> kk1<- list(a_c = 1:11, b = 6:10)
> 
> 
> I can do it with several lines of code. But can any one have idea to do efficiently/ quickly on a big data with less code.

Given that you used the term in your problem specification, it's hard to understand how you missed finding the `union` function :

kk1 <- with( kk, list( a_c <- union(a,c), b=b)  )
 kk1
#-----
[[1]]
 [1]  1  2  3  4  5 11 10  9  8  7  6

$b
[1] 10  9  8  7  6
#-----

(It's not a `merge`.)

I thought this would remove any factor-stored information, since the code (before bytecode compilation) is:

function (x, y) 
unique(c(as.vector(x), as.vector(y)))

But 'as.vector' does the equivalent of 'as.character' on factor vectors, so you would be "safe" from that concern.


-- 
David.

> Thanks in advance. 
> 
> Tanvir Ahamed 
> Göteborg, Sweden  |  mashranga at yahoo.com 
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list