Take the 2-minute tour ×

Right now I'm working with a character vector in R, that i use strsplit to separate word by word. I'm wondering if there's a function that I can use to check the whole list, and see if a specific word is in the list, and (if possible) say which elements of the list it is in.


a = c("a","b","c")
b= c("b","d","e")
c = c("a","e","f")

If z=list(a,b,c), then f("a",z) would optimally yield [1] 1 3, and f("b",z) would optimally yield [1] 1 2

Any assistance would be wonderful.

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

As alexwhan says, grep is the function to use. However, be careful about using it with a list. It isn't doing what you might think it's doing. For example:

grep("c", z)
[1] 1 2 3   # ?

grep(",", z)
[1] 1 2 3   # ???

What's happening behind the scenes is that grep coerces its 2nd argument to character, using as.character. When applied to a list, what as.character returns is the character representation of that list as obtained by deparsing it. (Modulo an unlist.)

[1] "c(\"a\", \"b\", \"c\")" "c(\"b\", \"d\", \"e\")" "c(\"a\", \"e\", \"f\")"

c("a", "b", "c") c("b", "d", "e") c("a", "e", "f")

This is what grep is working on.

If you want to run grep on a list, a safer method is to use lapply. This returns another list, which you can operate on to extract what you're interested in.

res <- lapply(z, function(ch) grep("a", ch))
[1] 1


[1] 1

# which vectors contain a search term
sapply(res, function(x) length(x) > 0)
share|improve this answer
Good explanation, good point –  alexwhan Jun 28 '13 at 6:39
Thanks for this input. I will definitely keep this in mind for my next project, where I will probably be doing something similar, but alexwhan's method suits my purposes well enough, and it's already started running. –  riders994 Jun 28 '13 at 6:42
add comment

You're looking for grep():

grep("a", z)
#[1] 1 3

grep("b", z)
#[1] 1 2
share|improve this answer
Huh, I thought that only worked on vectors... Thanks a lot! –  riders994 Jun 28 '13 at 6:16
Try is.vector(z). My prediction: You will be surprised. –  IShouldBuyABoat Jun 28 '13 at 6:42
That explains about a weeks worth of errors. –  riders994 Jun 28 '13 at 7:12
add comment

Your Answer


