27

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?

}
3
  • Please, provide some data we can work with.
    – patL
    Jan 11, 2018 at 10:56
  • added some code there,
    – yome
    Jan 11, 2018 at 10:58
  • In the tidyverse world, check out imap. No time now for a full answer, if someone wants to write one up or link to an answer using imap, please go ahead. Jun 8 at 21:24

2 Answers 2

36

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

}
3
  • you are cool for this answer. thanks.
    – bob
    Mar 18, 2022 at 21:09
  • Would the which way still be suitable if there are non unique entries in the list?
    – gernophil
    Jun 23 at 12:27
  • Did you try it? I think you will find it works, if I understand what you are asking.
    – Elin
    Jun 24 at 3:43
15

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.