简体   繁体   中英

Checking R list elements with common names

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

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"

With data.table::rbindlist :

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

#> [1] "ALERT"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM