r - Transpose list rows into a dataframe -


suppose list structure

lst=list(structure(c("level1", "level2", "level4", "level5","18", "abc", "pqr", "lmn"),          .dim = c(4l, 2l)),       structure(c("level1", "level2", "level3", "level5", "level6", "20", "xyz", "hive", "foo", "bar"),          .dim = c(5l, 2l)),      structure(c("level1", "level3", "level4", "level5","level6", "22", "dark", "yellow","foobar", "blue"),          .dim = c(5l, 2l)),      structure(c("level1", "level2", "level3", "level5","level6","level7","24", "dvd", "dxs","glass", "while","though"),       .dim = c(6l, 2l))      ) 

expecting o/p this

     level1 level2  level3  level4  level5  level6  level7 1)     18       abc     na      pqr     lmn     na      na 2)     20       xyz     hive    na      foo     bar     na 3)     22       na      dark    yellow  foobar  blue    na 4)     24       dvd     dxs     na      glass   while   though   

the first column list should transposed , accordingly, corresponding data should looked rows.

trying transpose of rows column giving error

 unique(t(list_temp[[c(1,2)]][,1])) error:error in list_temp[[c(1, 2)]][, 1] : incorrect number of dimensions 

also tried with

apply(list_temp,1,function(x){list_temp[[x]][,1]}) 

but gave me

error in apply(list_temp, 1, function(x) { :    dim(x) must have positive length 

any suggestion on how should done.

thanks.

two approaches:

1) using data.table-package

with:

library(data.table) dcast(rbindlist(lapply(lst, as.data.table), idcol = 'id'),       id ~ v1, value.var = 'v2')[, id := null][] 

you get:

   level1 level2 level3 level4 level5 level6 level7 1:     18    abc     na    pqr    lmn     na     na 2:     20    xyz   hive     na    foo    bar     na 3:     22     na   dark yellow foobar   blue     na 4:     24    dvd    dxs     na  glass  while though 

2) using base r

with:

reshape(transform(do.call(rbind.data.frame, lst),                   r = rep(seq_along(lst), lengths(lst)/2)),         idvar = 'r', timevar = 'v1', direction = 'wide')[,-1] 

you get:

   v2.level1 v2.level2 v2.level4 v2.level5 v2.level3 v2.level6 v2.level7 1         18       abc       pqr       lmn      <na>      <na>      <na> 5         20       xyz      <na>       foo      hive       bar      <na> 10        22      <na>    yellow    foobar      dark      blue      <na> 15        24       dvd      <na>     glass       dxs     while    though 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -