Tob
Tob

Reputation: 245

Match a list col in R

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

Answers (5)

akrun
akrun

Reputation: 886968

Using %in%

 which(sapply(mylist, function(x) 'a' %in% x))
[1] 1 3

Upvotes: 1

maydin
maydin

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

TarJae
TarJae

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

Anoushiravan R
Anoushiravan R

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

saz
saz

Reputation: 226

You can use grep:

grep("a",list(c("a", "b"), c("c")))

which gives

1

Upvotes: 1

Related Questions