Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Elements of Lists in R

Tags:

list

r

character

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.

ex.

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.

like image 844
riders994 Avatar asked Jun 28 '13 06:06

riders994


People also ask

How do I get the elements of a list in R?

Accessing List Elements. Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names.

How do you find the sum of elements in a list in R?

The sum() function in R to find the sum of the values in the vector.


1 Answers

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

as.character(z)
[1] "c(\"a\", \"b\", \"c\")" "c(\"b\", \"d\", \"e\")" "c(\"a\", \"e\", \"f\")"

cat(as.character(z))
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))
res
[[1]]
[1] 1

[[2]]
integer(0)

[[3]]
[1] 1


# which vectors contain a search term
sapply(res, function(x) length(x) > 0)
[1]  TRUE FALSE  TRUE
like image 174
Hong Ooi Avatar answered Oct 15 '22 01:10

Hong Ooi