Multiple unions

I try to make unions on several lists (in fact, they are objects of GRanges, not whole lists, but they are the same), basically one big union.

x<-sort(sample(1:20, 9)) y<-sort(sample(10:30, 9)) z<-sort(sample(20:40, 9)) mylists<-c("x","y","z") emptyList<-list() sapply(mylists,FUN=function(x){emptyList<-union(emptyList,get(x))}) 

It just returns the contents of the list. I need an equivalent

 union(x,union(y,z)) [1] 2 3 5 6 7 10 13 15 20 14 19 21 24 27 28 29 26 31 36 39 

but written in an extensible and not "variable explicit form" form

+7
source share
4 answers

Not necessarily an efficient memory paradigm that will work with GRanges,

 Reduce(union, list(x, y, z)) 

The argument may also be GRangesList(x, y, z) for the corresponding x values, etc.

+12
source
 unique(unlist(mget(mylists, globalenv()))) 

will do the trick. (Perhaps changing the environment specified when mget called, as needed.)

+1
source

OK, this works, but I'm curious why sapply seems to have its own scope

 x<-sort(sample(1:20, 9)) y<-sort(sample(10:30, 9)) z<-sort(sample(20:40, 9)) mylists<-c("x","y","z") emptyList<-vector() for(f in mylists){emptyList<-union(emptyList,get(f))} 
+1
source

I think it would be easier to separate the “dereferenced” part from the n-ary part of the compound, for example.

 dereflist <- function(l) lapply(a,get) nunion <- function(l) Reduce(union,l) 

But if you look at how the union works, you will see that you can also do

 nunion <- function(l) unique(do.call(c,l)) 

which is faster in all cases that I tested (much faster for long lists).

-s

+1
source

All Articles