0

Evening,

To begin, sorry this example is not so easy to reproduce but will try to explain.

I have a list and would like to average certain elements of this list called Model_eval_Mixed. An example of how I am working around it is below. I would like to average the AIC, Confusion_Matrix, Fixed, and so on from the original list but cannot. Is there a more concise alternative to the code below? Thank you in advance.

x <- sapply(Model_eval_Mixed, function(x)x["AIC"])
AIC <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["Confusion_Matrix"])
CM <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["Thresholds"])
Thrshlds <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["Fixed"])
Fixed <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["GP_par"])
GP_par <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["Optim_time"])
Optim_time <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["Specs1"])
Specs1 <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["Specs2"])
Specs2 <- Reduce('+',x)/length(x)

x <- sapply(Model_eval_Mixed, function(x)x["log_lik"])
log_lik <- Reduce('+',x)/length(x)

avg_mod <- list()
avg_mod[[1]] <- AIC
avg_mod[[2]] <- CM
avg_mod[[3]] <- Thrshlds
avg_mod[[4]] <- Fixed
avg_mod[[5]] <- GP_par
avg_mod[[6]] <- Optim_time
avg_mod[[7]] <- Specs1
avg_mod[[8]] <- Specs2
avg_mod[[9]] <- log_lik
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 28 '20 at 21:21

1 Answers1

0

It looks like this can be replaced with

cols <- c("AIC", "Confusion_Matrix", "Thresholds", "Fixed", 
          "GP_par", "Optim_time", "Specs1", "Specs2", "log_lik")

avg_mod <- lapply(cols, function(col) {
  x <- Model_eval_Mixed[col]
  Reduce('+',x)/length(x)
})

Hard to say for sure without a proper reproducible example.

MrFlick
  • 195,160
  • 17
  • 277
  • 295