Andrej
Andrej

Reputation: 3849

List of lists of lists into a data frame with purrr

Suppose we have the following list structure:

bla <- list(lda = list(list(auc1 = 0.85, auc2 = 0.56), list(auc1 = 0.65, auc2 = 0.72)),
            j48 = list(list(auc1 = 0.99, auc2 = 0.81), list(auc1 = 0.61, auc2 = 0.85)),
            c50 = list(list(auc1 = 0.92, auc2 = 0.59), list(auc1 = 0.68, auc2 = 0.80)))

The desired output is a data frame structured as:

    auc1 auc2
lda 0.85 0.56
lda 0.65 0.72
j48 0.99 0.81
j48 0.61 0.85
c50 0.92 0.59
c50 0.68 0.80

My attempt is pasted below. I'm able to purrr each inner list separately using the call:

bla[[1]] %>%
    map(., function(x) c(auc1 = x[["auc1"]],
                         auc2 = x[["auc2"]])) %>%
    map_dfr(., as.list)

Any idea is appreciated.

Upvotes: 2

Views: 630

Answers (2)

akrun
akrun

Reputation: 887971

We can also use rbindlist

library(data.table)
rbindlist(bla)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389325

Surprisingly only using bind_rows gives you what you want.

dplyr::bind_rows(bla)

This returns a tibble and tibbles don't have rownames.


You can do this in base R using do.call + rbind.

do.call(rbind, unlist(bla, recursive = FALSE))


#     auc1 auc2
#lda1 0.85 0.56
#lda2 0.65 0.72
#j481 0.99 0.81
#j482 0.61 0.85
#c501 0.92 0.59
#c502 0.68 0.8 

Upvotes: 4

Related Questions