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? }
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.
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.
Returns an INTEGER value that indicates the position of the target string within the source string.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With