Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

r

nested

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!

like image 496
Stefanie Richters Avatar asked Sep 17 '25 13:09

Stefanie Richters


1 Answers

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.

like image 63
Maël Avatar answered Sep 19 '25 05:09

Maël