Select a subset of lists from a list of lists

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 

Results:

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

Is it possible to do this without a for loop or something else?

I tried to select [[i]][[1]]==0.4 , but it only returns true conditions. What if I want to choose based on several conditions? For example, [[i]][[1]]==0.4 & [[i]][[2]]==0.9

+7
r
source share
1 answer

You can use something like:

 ll[which(sapply(ll, `[[`, 1) == .4)] 

But you may run into floating point problems ....


Here is 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 a few conditions is pretty similar:

 ll[which(sapply(ll, `[[`, 1) == .4 & sapply(ll, `[[`, 2) == 1)] # [[1]] # [[1]][[1]] # [1] 0.4 # # [[1]][[2]] # [1] 1 
+6
source share

All Articles