Home > other >  R - find cases in list of lists which meet specific condition
R - find cases in list of lists which meet specific condition

Time:01-04

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!

CodePudding user response:

Perhaps this helps

 which(sapply(mylist, \(x) sapply(x, \(y) all(y == 'TRUE'))), arr.ind = TRUE)

or use

lapply(mylist, \(x) Filter(\(y) all(y == 'TRUE'), x))
[[1]]
list()

[[2]]
[[2]][[1]]
[1] "TRUE" "TRUE" "TRUE"

[[2]][[2]]
[1] "TRUE" "TRUE" "TRUE"


[[3]]
[[3]][[1]]
[1] "TRUE" "TRUE" "TRUE"

CodePudding user response:

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.

  • Related