r - rbindlist data.tables different dimensions -


i perform function multiple times different outputs exemplified.

require(data.table) myfunction<-function(x){ dt1<-data.table(a=c(1,2,3),b=c("a","b","c")) dt2<-data.table(d=c(4,5,6), e=c("d","e","f")) return(list(dt1=dt1, dt2=dt2)) } result<-lapply(1:2, myfunction) 

i want bind results. desired output 1 showing. real example uses hundreds of tables.

l1<-rbindlist(list(result[[1]]$dt1, result[[2]]$dt1), idcol = true) l2<-rbindlist(list(result[[1]]$dt2, result[[2]]$dt2), idcol = true) desired_output<-list(l1, l2) 

i use option not working: rbindlist data.tables wtih different number of columns

======================================================================

update

the option @nicola proposed doesn´t work when number of elements of list diferent 2. first example (dt1 , dt2). solution create variable "l" calculate number of elements inside list of function.

new example solution.

require(data.table) myfunction<-function(x){ dt1<-data.table(a=c(1,2,3),b=c("a","b","c")) dt2<-data.table(d=c(4,5), e=c("d","e")) dt3<-data.table(f=c(7,8,na,9), g=c("g","h","i","j")) return(list(dt1=dt1, dt2=dt2, dt3=dt3)) } result<-lapply(1:5, myfunction)  l<-unique(sapply(result, length)) apply(matrix(unlist(result,recursive=false),nrow=l),1,rbindlist,idcol=true) 

here's option:

do.call(function(...) map(function(...) rbind(..., idcol = t), ...), result) #$dt1 #   .id b #1:   1 1 #2:   1 2 b #3:   1 3 c #4:   2 1 #5:   2 2 b #6:   2 3 c # #$dt2 #   .id d e #1:   1 4 d #2:   1 5 e #3:   1 6 f #4:   2 4 d #5:   2 5 e #6:   2 6 f 

here's another:

lapply(purrr::transpose(result), rbindlist, idcol = t) 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -