I have a list of lists of the following form:
[[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 would like to select all lists that have 0.4 in their [[i]][[1]]
.
That is, select
[[i]][[1]]==0.4
The results would be:
[[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]]
Can this be done without a for
loop or something?
I tried selecting [[i]][[1]]==0.4
, but it only returns truth conditions. What if I want to select based on multiple conditions? For example, [[i]][[1]]==0.4 & [[i]][[2]]==0.9
You can use something like:
ll[which(sapply(ll, `[[`, 1) == .4)]
But you might run into floating point problems....
Here's an MRE:
A list
with 4 items.
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
Apply the proposed solution:
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
Adding multiple conditions is pretty similar:
ll[which(sapply(ll, `[[`, 1) == .4 & sapply(ll, `[[`, 2) == 1)]
# [[1]]
# [[1]][[1]]
# [1] 0.4
#
# [[1]][[2]]
# [1] 1
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