Home > Software design >  How to select lists elements in a large list based on sub-elements inside every element list?
How to select lists elements in a large list based on sub-elements inside every element list?

Time:11-16

I have a large list that has many combinations of character variables from a data.frame. My goal is subset the combinations that have a character sub-element ("var_pib_nsa_interanual") inside every list element that have that, and delete others. In other words, I want delete lists elements that don't have an especific sub-element and keep that have.

I tried many alternatives, but any of them are good enough.

An image of the list

I tried:

sapply(x, function(x) any(x[1] == "var_pib_nsa_interanual", na.rm = T))

lapply(x,"[","var_pib_nsa_interanual")

And others.

CodePudding user response:

We can use the base Filter function.

# example list
ex = list(
  "a",
  "var_pib_nsa_interanual",
  c('a', "var_pib_nsa_interanual"),
  "no"
)

Filter(\(x) "var_pib_nsa_interanual" %in% x, ex)
# [[1]]
# [1] "var_pib_nsa_interanual"
# 
# [[2]]
# [1] "a"                      "var_pib_nsa_interanual"
  • Related