0

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

$item2
[1] FALSE

Comments

0

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.