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)))
Since you know the exact dimensions of your returned object you can use
vapply
in cases like this for a minor performance improvement:However, the resulting object can be hard to work with.