Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

r - Find String in Any Elements of a List and Then Use the Name of That List Element

$
0
0

I am trying see if the string exists in any of the elements in a list and then use the name of that list if it does exist.

Right now, I am using case_when and grepl, but I'd like a more efficient way to look through my named_list and then use the name.


fruit <- c("apple", "banana", "pear")
drinks <- c("beer", "wine", "coffee")
stuff <- c("chair", "couch", "desk")


df <- data.frame(foo = sample(x = c(fruit, drinks, stuff), size = 10, replace = T),
                 x = sample(1:500, size = 10, replace = T))

df

# foo    x
# pear   449
# wine   241
# pear   53
# couch  72
# banana 443
# coffee 172
# desk   126
# desk   183
# desk   7
# banana 73

df %>%
  mutate(category = case_when(grepl(paste0(fruit, collapse = "|"), foo, ignore.case = T) ~ "fruit",
                              grepl(paste0(drinks, collapse = "|"), foo, ignore.case = T) ~ "drinks",
                              grepl(paste0(stuff, collapse = "|"), foo, ignore.case = T) ~ "stuff"))

# foo    x   category
# pear   449 fruit
# wine   241 drinks
# pear   53  fruit
# couch  172 stuff
# banana 443 fruit
# coffee 172 drinks
# desk   126 stuff
# desk   183 stuff
# desk   7   stuff
# banana 73  fruit

# create named list of lists/vectors
named_list <- Hmisc::llist(fruit, drinks, stuff)
named_list

Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>