user6559913 user6559913 - 2 months ago 10
R Question

how to subset a list on basis of multiple conditions in R?

I have a list containing value, level, id, colorvalue, actual value, A,B, change, name and parent. I want to subset "value" greater than 1000 at "level" = 2 only. It should subset only for level 2, there are 2,3,4 levels in list. Actually, data is in format of data tree having hierarchies, the levels are like layers starting from 2,3,4. So, what I actually want to achieve is that for level 2 only the value should be filtered on basis of conditions and other levels should remain same. So finally I should have all data from level 2,3,4 and level 2 having values > 1000 only.

list :

[[1]]
[[1]]$value
[1] 19.48275

[[1]]$level
[1] 4

[[1]]$id
[1] "10"

[[1]]$colorValue
[1] 4244.56

[[1]]$actualvalue
[1] 4244.56

[[1]]$A
[1] 21786.25

[[1]]$B
[1] 17541.69

[[1]]$change
[1] 19.48275

[[1]]$name
[1] "HFSS"

[[1]]$parent
[1] "7"


[[2]]
[[2]]$value
[1] Inf

[[2]]$level
[1] 4

[[2]]$id
[1] "100"


Is there any possible way to achieve this?

Answer

We can use lapply to loop through the list and filter the list elements based on the condition in the OP's post.

lapply(lst, function(x) x[(x[["value"]] > 1000 & x[["level"]]==2)|x[["level"]]!=2])
Comments