How do I get the name of a vector within a named list using the names of elements in the vector?

For example, a named list like the one below, how do I the result 'SECOND' from 'Apr'?

x = list( 'FIRST' = c('Jan', 'Feb', 'Mar'), 'SECOND' = c('Apr', 'May', 'Jun'), 'THIRD' = c('Jul', 'Aug', 'Sept'), 'FOURTH' = c('Oct', 'Nov', 'Dec')

Not very elegant

x = list( 'FIRST' = c('Jan', 'Feb', 'Mar'), 
          'SECOND' = c('Apr', 'May', 'Jun'), 
          'THIRD' = c('Jul', 'Aug', 'Sept'), 
          'FOURTH' = c('Oct', 'Nov', 'Dec'))
MyFunc <- function(vec, key) key %in% vec
Bools <- sapply(X = x, MyFunc, key = "Apr")
names(x[Bools])
#> [1] "SECOND"

Created on 2020-07-14 by the reprex package (v0.3.0)

2 Likes

Thank you so much!!!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.