apply a function to some elements of a nested lists in R

345 views Asked by At

I wish to apply a function only to some elements of a nested list

l <- list()

l$a$forecast <- rnorm(3)
l$a$model <- "arima"
l$b$forecast <- rnorm(3)
l$b$model <- "prophet"

The desired output would be like this: applying the sum function to the $forecast element of the list

fcst <- c(sum(l$a$forecast),sum(l$b$forecast))
mdl <- c(l$a$model,l$b$model)
df <- data.frame(fcst,mdl)

I tried something like this:

df <- lapply(l$forecast, function(x) sum(x))
df <- do.call(rbind, Map(cbind, sku = names(df)))
3

There are 3 answers

0
bcarlsen On BEST ANSWER

do.call(
  rbind,
  lapply(
    l,
    function(x) list(fcst = sum(x$forecast), model = x$model)
  )
)

Since you know the exact dimensions of your returned object you can use vapply in cases like this for a minor performance improvement:

vapply(
  l,
  FUN = function(x) list(fcst = sum(x$forecast), model = x$model),
  FUN.VALUE = list(fcst = numeric(1), model = character(1))
)

However, the resulting object can be hard to work with.

1
Joris C. On

Another approach using rrapply() in the rrapply-package combined with dplyr's bind_rows(). This also extends to lists containing deeper nested levels.

rrapply::rrapply(l, condition = function(x, .xname) .xname == "forecast", f = sum) %>%
  dplyr::bind_rows()

#> # A tibble: 2 x 2
#>   forecast model  
#>      <dbl> <chr>  
#> 1    -1.28 arima  
#> 2     1.10 prophet

Data

set.seed(1)

l <- list(
  a = list(forecast = rnorm(3), model = "arima"),
  b = list(forecast = rnorm(3), model = "prophet")
)
0
Ricardo Semião On

You can get the letters with the object letters, then using its output in a loop:

    n = 2 #number of lists you have
    sumfore = model = vector()
    for(i in letters[seq(1,n,1)]){
      sumfore[i] = sum(l[[i]]$forecast)
      model[i] =l[[i]]$model}
    newdf = data.frame(sumfore, model)