Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a subset of lists from list of lists

Tags:

r

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

like image 211
upabove Avatar asked Sep 01 '13 08:09

upabove


1 Answers

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
like image 55
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 20 '22 10:10

A5C1D2H2I1M1N2O1R2T1