I have a large list of lists with three columns (TRUE/FALSE) per case. I want to find out for which cases all three columns = TRUE.
Example data:
l1 <- list( c("TRUE","FALSE","FALSE") , c("FALSE","FALSE","FALSE") , c("FALSE","FALSE","FALSE") )
l2 <- list( c("TRUE","TRUE","TRUE") , c("TRUE","TRUE","TRUE") , c("FALSE","FALSE","FALSE") )
l3 <- list( c("TRUE","TRUE","TRUE") , c("FALSE","FALSE","FALSE") , c("TRUE","FALSE","FALSE") ) 
mylist <- list(l1,l2,l3)
In the output I need to see which cases in which lists meet the condition, so something like l2[[1]] l3[[1]]
Hope that someone can help! Thank you so much in advance!
With rapply:
rapply(mylist, \(x) all(x == "TRUE"), how = "list")
output
[[1]]
[[1]][[1]]
[1] FALSE
[[1]][[2]]
[1] FALSE
[[1]][[3]]
[1] FALSE
[[2]]
[[2]][[1]]
[1] TRUE
[[2]][[2]]
[1] TRUE
[[2]][[3]]
[1] FALSE
[[3]]
[[3]][[1]]
[1] TRUE
[[3]][[2]]
[1] FALSE
[[3]][[3]]
[1] FALSE
Or, if you want a more compact result:
rapply(mylist, \(x) all(x == "TRUE"), how = "list") |>
  lapply(\(x) which(unlist(x)))
[[1]]
integer(0)
[[2]]
[1] 1 2
[[3]]
[1] 1
Another compact solution with rrapply::rrapply:
rrapply::rrapply(mylist, \(x) all(x == "TRUE"), how = "melt")
  L1 L2            value
1  2  1 TRUE, TRUE, TRUE
2  2  2 TRUE, TRUE, TRUE
3  3  1 TRUE, TRUE, TRUE
Note: you probably have logical vector in your real data, which is made of c(TRUE, FALSE) (without the brackets). In that case, all(x), is sufficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With