jackson
jackson

Reputation: 633

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.

Upvotes: 8

Views: 15363

Answers (2)

IRTFM
IRTFM

Reputation: 263352

Use which.max instead of which. It will pick out the position of the first TRUE since TRUE > FALSE.

 which.max(a.vector=="a")
#[1] 1

It's possible that @James understood your request better than I. You really asked a different question at the end of your text than you asked in the subject line so you might wnat to clarify. I will add that the notion of passing the location of "i" in a hidden form along with its value is rather foreign to R. People often ask whether R is "pass by value" versus "pass by reference". The correct answer is neither... that it is "pass by promise". However, that is conceptually a lot closer to "pass by value" than it would be to "pass by reference". for is a function and R makes a copy of the arguments being passed from the function invocation into its body. There is no "location" information that gets carried along unless such information is what you do in fact asked it to pass.

Upvotes: 1

James
James

Reputation: 66844

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]
   ...
}

Upvotes: 15

Related Questions