How to get index in a loop in R

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))

}

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.

Tags:

Loops

R