Searching for a character in a named list in R

59 Views Asked by At

I have a named list and want to search if a character string appears in it.

data_list <- list()
data_list$item1 <- c("hello_world"="hi", "snooker cue"="cue")
data_list$item2 <- c("property"="house")

When I see if "cue" is in the list by doing "cue"%in%data_list the result is FALSE but it is in there under data_list$item1. How can I search to see if strings appear in the list and return TRUE if they do?

3

There are 3 best solutions below

0
Maël On

unlist your data to access the list elements:

"cue" %in% unlist(data_list)
#[1] TRUE

Note here that %in% returns one value for each of the left operand (here, just "cue"), can be interpreted "is the left value(s) contained in the right vector". On the contrary, == will return one value for each of the left operand and can only accept a vector of length 1 on the left side.

0
Friede On

If the location (item) should be returned as well:

> lapply(data_list, \(v) "cue" %in% v)
$item1
[1] TRUE

$item2
[1] FALSE
0
jay.sf On

Have you tried grepl?

> grepl('cue', unlist(data_list)) |> any()
[1] TRUE

Data:

> dput(data_list)
list(item1 = c(hello_world = "hi", `snooker cue` = "cue"), item2 = c(property = "house"))