R: Using element location information when passing through a vector.

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

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

Suppose I need the index of the "first" "a" of the vector. Can not use

which (a.vector == "a")

Because there are two “a's,” and it will return two positions 1 and 4. I need a specific index of the element, which the loop instantly covers.

I need this 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 is similar to the enumerate function in python. The solution will help a lot. Thanks.

+6
source share
2 answers

How about just a loop with an index number?

 for (i in seq_along(a.vector)){ a.element <- a.vector[i] b.element <- b.vector[i] ... } 
+12
source

Use which.max instead of which . He will choose the position of the first TRUE, since TRUE> FALSE.

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

Perhaps @James understood your request better than I did. You really asked a different question at the end of your text than you asked in the subject line so you can clarify. I will add that the concept of transferring the location “i” in a latent form along with its meaning is quite foreign to R. People often ask if R is a “transition by value” compared to “transition by reference.” The correct answer is neither ... that it "passes by promise." However, this is conceptually much closer to a "jump by value" than a "jump by reference." for is a function, and R is a copy of the arguments passed from the function call to its body. “Location information” does not apply unless such information is what you really requested to transmit.

+1
source

Source: https://habr.com/ru/post/908337/


All Articles