Reputation: 245
I have a list of vectors and I want to get the index in the list where a value is in the vector. I've tried using match()
but it returns NA if the vector has a length greater than one.
For example match("a", list(c("a", "b"), c("c")))
returns NA
but I would need it to return 1
.
Thanks in advance!
Upvotes: 4
Views: 109
Reputation: 3755
You can use sapply()
to get the index of the vector inside the list,
which(!is.na(sapply(mylist ,function(x) match("a",x))))
#[1] 1 3
Data:
mylist <- list(c("a", "b"), c("c"),c("d","e","f","a"))
Upvotes: 0
Reputation: 78917
match
works. first unlist
match("a", unlist(list(c("a", "b"), c("c"))))
Output:
> match("a", unlist(list(c("a", "b"), c("c"))))
[1] 1
Upvotes: 1
Reputation: 21908
Or we could use purrr
package functions. (Using @maydin's sample data and thanks for that):
library(purrr)
imap(mylist, ~ if("a" %in% .x) .y) %>%
discard(is.null)
[[1]]
[1] 1
[[2]]
[1] 3
Upvotes: 2