Home > Mobile >  Checking R list elements with common names
Checking R list elements with common names

Time:01-19

I have a nested R list with the following structure:

my_list <- list(a = list(value = 1, alert = FALSE), b = list(value = 2, alert = FALSE), c = list(value = 3, alert = TRUE))

Is there logic to determine whether all the elements named alert are FALSE? For example:

ifelse(<all mylist["alerts"] are FALSE>, print("No alerts to report!"), print("ALERT"))

> ALERT

CodePudding user response:

With data.table::rbindlist:

c("NO ALERT", "ALERT")[1 1*any(data.table::rbindlist(my_list)$alert)]

#> [1] "ALERT"

CodePudding user response:

You can try this with sapply

In the general case

ifelse(all(sapply(my_list, function(x) x["alert"]==F)),
  "No alerts to report!","ALERT")
[1] "ALERT"

Using the logical values directly as pointed out by @Ritchie Sacramento

ifelse(any(sapply(my_list, function(x) !x["alert"][[1]])),
  "ALERT", "No alerts to report!")
[1] "ALERT"
  •  Tags:  
  • Related