Rilcon42 Rilcon42 - 3 months ago 8
R Question

returning list of lists as dataframe

What is the correct way to record the results of the inner

lapply
call here? My end goal is a dataframe with
percentage_accuracy
,
statparam
, and
cutoff
for each value tested. Is there a more "R" way to do this?

best<-lapply(1:100,function(i){
statval<-sample.int(c(1,0),100,replace=T)
lapply(1:100,function(j){
aaa<-statval+j*27
list(percentage_accuracy=aaa,statparam=i,cutoff=j)
})
})

Answer

We can convert the inner most to data.frame, rbind it and then do the rbind on the outer most loop.

 d1 <- do.call(rbind, lapply(best, function(x) do.call(rbind, lapply(x, data.frame) )))
 str(d1)
 #'data.frame':   1000000 obs. of  3 variables:
 #$ percentage_accuracy: num  28 28 28 28 28 28 28 28 28 28 ...
 #$ statparam          : int  1 1 1 1 1 1 1 1 1 1 ...
 #$ cutoff             : int  1 1 1 1 1 1 1 1 1 1 ...

If this needs to be faster, use rbindlist

library(data.table)
d2 <- rbindlist(lapply(best, function(x) rbindlist(lapply(x, data.frame))))
Comments