0

I have a variable that evaluates to T/F if a variable named "aic" exists.

aic_exist <- c("aic" %in% names(fexp_list[[i]]), "aic" %in% names(fg_list[[i]]), "aic" %in% names(fln_list[[i]]), "aic" %in% names(fnorm_list[[i]]), "aic" %in% names(funif_list[[i]]), "aic" %in% names(fw_list[[i]])).

aic_exist evaluates to [1] FALSE TRUE TRUE TRUE TRUE TRUE.

I would like to create another variable aic_values that contains only values using the aic_exist variable. i.e. not include fexp_list as there is no aic value.

Something like aic_values <- (c(fexp_list[[i]][["aic"]], fg_list[[i]][["aic"]], fln_list[[i]][["aic"]], fnorm_list[[i]][["aic"]], funif_list[[i]][["aic"]], fw_list[[i]][["aic"]])) but comparing to aic_exist?

phald
  • 7
  • 1

1 Answers1

1

Let's put all your lists in a bigger list:

big_list <- list(
  fexp_list[[i]],
  fg_list[[i]],
  fln_list[[i]],
  fnorm_list[[i]],
  funif_list[[i]],
  fw_list[[i]]
)

aic_exist <- sapply(big_list, function(x) "aic" %in% names(x))
## extract AIC from the elements it exists in
aic_values <- sapply(big_list[aic_exist], "[[", "aic")

The [[i]] makes me think you're doing this in a loop... if you share more context, there might be a better way. The purrr package has many utilities for dealing with lists. It might be possible to do it all in a line or two with something like below (untested obviously):

library(purrr)
big_list = 
map_depth(list(fexp_list, fg_list, fln_list, ...), .depth = 3, pluck, "aic")
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Works well, thanks. Hadn't come across the ```sapply``` function yet. – phald May 12 '21 at 14:41
  • [This FAQ](https://stackoverflow.com/a/7141669/903061) is a good introduction to the apply family of functions. – Gregor Thomas May 12 '21 at 14:43
  • Apologies in advance for reopening a closed question; but if instead I wanted to insert `NULL` where the `aic_exist` variable evaluates to `TRUE`, what changes would need to be made to the sapply function? – phald May 14 '21 at 15:27
  • I have also just seen your updated answer with `purr' package suggestion and using the pluck function. It looks like it will be helpful as I can see already it returns NA if an element is not present in the list – phald May 14 '21 at 15:35