Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index in a loop in R

Tags:

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?  } 
like image 435
yome Avatar asked Jan 11 '18 10:01

yome


People also ask

How do you find the index of a loop?

Using enumerate() method to access index enumerate() is mostly used in for loops where it is used to get the index along with the corresponding element over the given range.

Can the index in a for loop be a variable?

Required (static): You cannot index or subscript the loop variable in any way. This restriction is required, because referencing a field of a loop variable cannot guarantee the independence of iterations.

Is there an index function in R?

Returns an INTEGER value that indicates the position of the target string within the source string.

Can you index a list in R?

R has main 3 indexing operators. They are as follows : [ ] = always returns a list with a single element. [[ ]] = returns a object of the class of item contained in the list.


2 Answers

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))  } 
like image 137
Elin Avatar answered Dec 01 '22 22:12

Elin


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.

like image 39
steevee Avatar answered Dec 01 '22 21:12

steevee