r - How can I flatten two lists within a list without using data.table? -


i form 1 data.frame lists within list

l1 <- list(a = c(1, 2, 3), b = c(5, 6, 7)) l2 <- list(a = c(11, 22, 33), b = c(15, 16, 17)) l3 <- list(l1, l2) l3  library(data.table) 

according 'data.table' manual : "'rbindlist' same do.call("rbind",l), faster"

i achieve 'rbindlist' using r base package

rbindlist need 'do.call' not!

rbindlist(l3) 

do.call not want

do.call(rbind, l3)  identical(rbindlist(l3), do.call(rbind, l3)) 

i'd think calling as.data.frame each time costly. how about?

as.data.frame(do.call(mapply, c(l3, fun=c, simplify=false))) 

mapply takes first elements of l3 , applies function fun, 2nd element , on... suppose you'd 2 lists (l3[[1]] , l3[[2]]), you'd do:

mapply(fun=c, l3[[1]], l3[[2]], simplify=false) 

here simplify=false makes sure output not converted (or simplified) matrix. it'll list. general case, use do.call , pass our list other arguments function mapply. hope helps.


benchmarking on big data:

ll <- unlist(replicate(1e3, l3, simplify=false), rec=false)  aa <- function() as.data.frame(do.call(mapply, c(ll, fun=c, simplify=false))) bb <- function() do.call(rbind, lapply(ll, as.data.frame))  require(microbenchmark) microbenchmark(o1 <- aa(), o2 <- bb(), times=10)  unit: milliseconds        expr        min         lq     median         uq      max neval  o1 <- aa()   4.356838   4.931118   5.462995   7.623445  20.5797    10  o2 <- bb() 673.773795 683.754535 701.557972 710.535860 724.2267    10  identical(o1, o2) # [1] true 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -