我有以下表格的清单清单:
[[1]]
[[1]][[1]]
[1] 0.4
[[2]]
[1] 0.3
[[3]]
[1] 9
[[4]]
[1] 10
[[5]]
[1] 0.4
[[2]]
[[2]][[1]]
[1] 0.4
[[2]]
[1] 0.4
[[3]]
[1] 99
[[4]]
[1] 4
[[5]]
[1] 3
[[3]]
[[3]][[1]]
[1] 0.3
[[2]]
[1] 0.3
[[3]]
[1] 2
[[4]]
[1] 08
[[5]]
...
[[100]]
[[100]][[1]]
[1] 0.4
[[2]]
[1] 0.1
[[3]]
[1] 0
[[4]]
[1] 7
[[5]]
我想选择[[i]][[1]]
中有0.4的所有列表。
即,选择
[[i]][[1]]==0.4
结果将是:
[[1]]
[[1]][[1]
[1] 0.4
[[2]]
[1] 0.3
[[3]]
[1] 9
[[4]]
[1] 10
[[5]]
[1] 0.4
[[2]]
[[2]][[1]]
[1] 0.4
[[2]]
[1] 0.4
[[3]]
[1] 99
[[4]]
[1] 4
[[5]]
[1] 3
...
[[100]]
[[100]][[1]]
[1] 0.4
[[2]]
[1] 0.1
[[3]]
[1] 0
[[4]]
[1] 7
[[5]]
这可以在没有for
循环的情况下完成吗?
我尝试选择[[i]][[1]]==0.4
,但它只返回真值条件。如果我想根据多个条件选择怎么办?例如,[[i]][[1]]==0.4 & [[i]][[2]]==0.9
答案 0 :(得分:8)
您可以使用以下内容:
ll[which(sapply(ll, `[[`, 1) == .4)]
但是你可能遇到浮点问题......
这是一个MRE:
包含4个项目的list
。
ll <- list(list(.4, 1), list(.1, 2), list(.3, 3), list(.4, 4))
# [[1]]
# [[1]][[1]]
# [1] 0.4
#
# [[1]][[2]]
# [1] 1
#
#
# [[2]]
# [[2]][[1]]
# [1] 0.1
#
# [[2]][[2]]
# [1] 2
#
#
# [[3]]
# [[3]][[1]]
# [1] 0.3
#
# [[3]][[2]]
# [1] 3
#
#
# [[4]]
# [[4]][[1]]
# [1] 0.4
#
# [[4]][[2]]
# [1] 4
应用建议的解决方案:
ll[which(sapply(ll, `[[`, 1) == .4)]
# [[1]]
# [[1]][[1]]
# [1] 0.4
#
# [[1]][[2]]
# [1] 1
#
#
# [[2]]
# [[2]][[1]]
# [1] 0.4
#
# [[2]][[2]]
# [1] 4
添加多个条件非常相似:
ll[which(sapply(ll, `[[`, 1) == .4 & sapply(ll, `[[`, 2) == 1)]
# [[1]]
# [[1]][[1]]
# [1] 0.4
#
# [[1]][[2]]
# [1] 1