yome
yome

Reputation: 3103

How to get index in a loop in R

I have a vector of character type which has all the list of names.

So I'm looping through each name and peforming some actions. This loop is not based on the index/length (and I want to keep it this way).

However, if I want to access the index value in the loop how do I get it.

Ex:

names <- c("name1", "name2")

for(name in names){

#do something
print(name)

#here how would I get the index number? like 1, 2 etc?

}

Upvotes: 28

Views: 54664

Answers (2)

steevee
steevee

Reputation: 2538

For variety:

names <- c("name1", "name2")
for(i in seq_along(names)){
    print(i)
}

seq_along is a fast primitive, and IMO slightly sweeter syntactic sugar.

Upvotes: 17

Elin
Elin

Reputation: 6755

You can do something like this, which is literally getting the i value.

names <- c("name1", "name2")
i<-0
for(name in names){
    i<-i+1
    print(i)

}

Or change the loop to use a numeric index

names <- c("name1", "name2")
for(i in 1:length(names)){
    print(i)

}

Or use the which function.

names <- c("name1", "name2")
for(name in names){

    print(which(name == names))

}

Upvotes: 39

Related Questions