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

12,375

Solution 1

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

Solution 2

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.

Share:
12,375
jackson
Author by

jackson

Updated on June 05, 2022

Comments

  • jackson
    jackson almost 2 years

    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.

  • jackson
    jackson about 12 years
    Many thanks for the information on 'pass by'. Actually, its the location information that I wanted to use in passing-by. It's true that the subject line and the question are a little incoherent. The subject line makes any sense only if its connected to looping. It's like pointing a finger to an element of a vector, and asking it's index. I used the word 're-occurrence' in the wrong sense that it meant 'occurrences before or after the position of the element.' For the answer, the first TRUE can also be got simply by using which(...)[1]. Hope the new sub. line is better. Thanks a lot.