user6559913 user6559913 - 1 year ago 100
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] 19.48275

[1] 4

[1] "10"

[1] 4244.56

[1] 4244.56

[1] 21786.25

[1] 17541.69

[1] 19.48275

[1] "HFSS"

[1] "7"

[1] Inf

[1] 4

[1] "100"

Is there any possible way to achieve this?

Answer Source

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])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download