Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Using position information of elements when looping through a vector.

When looping through a vector, is it possible to use the index of an element along with the element?

a.vector<-c("a", "b", "c", "a", "d")

Let's suppose I need the index of the 'first' "a" of a.vector. One can't use

which(a.vector == "a")

Because there are two 'a' s and it would return two positions 1 and 4. I need the specific index of the element which the loop is instantly covering.

I need it for something like this:

b.vector<-c("the", "cat", "chased", "a", "mouse")

for (i in a.vector) {
    element<-b.vector[INDEX.OF(a.vector)])
-------some process using both 'element' and "a"-------}

This seems similar to the 'enumerate' function in python. A solution would help a lot. Thanks.

like image 385
jackson Avatar asked Feb 13 '12 15:02

jackson


1 Answers

How about just looping with the index number?

for (i in seq_along(a.vector)){
   a.element <- a.vector[i]
   b.element <- b.vector[i]
   ...
}
like image 183
James Avatar answered Sep 23 '22 13:09

James