R -在满足特定条件的列表列表中查找案例

du7egjpx  于 2023-01-06  发布在  其他
关注(0)|答案(3)|浏览(132)

我有一个很大的列表,每种情况下有三列(TRUE/FALSE)。我想找出在哪些情况下所有三列都为TRUE。
示例数据:

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)

在输出中,我需要查看列表满足条件的情况,例如l2 1 l3 1
希望有人能帮上忙!先谢谢你了!

mpbci0fu

mpbci0fu1#

使用rapply

rapply(mylist, \(x) all(x == "TRUE"), how = "list")

输出

[[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

或者,如果要获得更紧凑的结果:

rapply(mylist, \(x) all(x == "TRUE"), how = "list") |>
  lapply(\(x) which(unlist(x)))

[[1]]
integer(0)

[[2]]
[1] 1 2

[[3]]
[1] 1

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

注意:你的真实的数据中可能有逻辑向量,它是由c(TRUE, FALSE)(没有括号)组成的,在这种情况下,all(x)就足够了。

o75abkj4

o75abkj42#

也许这能帮上忙

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

或使用

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"

或者可能是

> lapply(mylist, \(x) lapply(x, \(y) all(y == 'TRUE')))
[[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
6vl6ewon

6vl6ewon3#

下面是使用lapply的另一个技巧

lapply(
  mylist,
  function(x) {
    as.list(
      colMeans(type.convert(list2DF(x), as.is = TRUE)) == 1
    )
  }
)

它给出了

[[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

相关问题