Extracting outputs from lapply to a dataframe Extracting outputs from lapply to a dataframe r r

Extracting outputs from lapply to a dataframe


Try this if results were your list:

> as.data.frame(do.call(rbind, results))     V1   V21  amer 14.52  appl 14.23  brec 13.14  camb 13.5...


One option might be to use the ldply function from the plyr package, which will stitch things back into a data frame for you.

A trivial example of it's use:

ldply(1:10,.fun = function(x){c(runif(1),"a")})                    V1 V21    0.406373084755614  a2    0.456838687881827  a3    0.681300171650946  a4    0.294320539338514  a5    0.811559669673443  a6    0.340881009353325  a7    0.134072444401681  a8  0.00850683846510947  a9    0.326008745934814  a10    0.90791508089751  a

But note that if you're mixing variable types with c(), you probably will want to alter your function to return simply data.frame(name= name,value = value) instead of c(name,value). Otherwise everything will be coerced to character (as it is in my example above).


inp <- list(c("amer", "14.5"), c("appl", "14.2"), .... # did not see need to copy alldata.frame( first= sapply( inp, "[", 1),             second =as.numeric( sapply( inp, "[", 2) ) )   first second1   amer   14.52   appl   14.23   brec   13.14   camb   13.55   camo   30.16   cari   13.8snipped output