1

I have the following list structure

ts1 <- ts(rnorm(10))
l <- list()
l[["P1"]][["M1"]][["forecast"]] <- rnorm(1)
l[["P1"]][["M1"]][["accuracy"]] <- rnorm(1)
l[["P1"]][["M1"]][["forecast"]] <- rnorm(1)
l[["P1"]][["M1"]][["accuracy"]] <- rnorm(1)
l[["P2"]][["M2"]][["forecast"]] <- rnorm(1)
l[["P2"]][["M2"]][["accuracy"]] <- rnorm(1)
l[["P2"]][["M2"]][["forecast"]] <- rnorm(1)
l[["P2"]][["M2"]][["accuracy"]] <- rnorm(1)

I wish to convert it to a data frame with the following columns: Note that I only want one of the elements of the final list

df <- data.frame(Product=c("p1","p1","p2","p2"),model=c("M1","M2","M1","M2"),accuracy=c(l$P1$M1$accuracy,l$P1$M2$accuracy,l$P2$M1$accuracy,l$P2$M2$accuracy))

I tried something like this:

df <- lapply(l, function(x) do.call(rbind,x))
df <- do.call(rbind,Map(cbind,product=names(df),df))
as.data.frame(df)

But I don´t manage to get the names properly

2 Answers 2

1

In base R, you could try something like this :

tmp <- lapply(l, function(x) {
  df <- do.call(rbind,x)
  data.frame(df, model = rownames(df))
})
do.call(rbind, Map(cbind, tmp, Product = names(tmp)))

#     forecast   accuracy model Product
#P1 -0.6148388 -0.6326906    M1      P1
#P2  0.1245955  0.9269495    M2      P2

However, it is shorter with tidyverse functions.

library(dplyr)
library(purrr)

map_df(l, ~bind_rows(.x, .id = 'model'), .id = 'product')

#  product model forecast accuracy
#  <chr>   <chr>    <dbl>    <dbl>
#1 P1      M1      -0.615   -0.633
#2 P2      M2       0.125    0.927
Sign up to request clarification or add additional context in comments.

Comments

1

An option with data.table

library(data.table)
rbindlist(lapply(l, rbindlist, idcol = 'model'), idcol = 'product')
#   product model   forecast  accuracy
#1:      P1    M1 0.72132201 0.9557613
#2:      P2    M2 0.01656428 0.8460819

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.