Iterations in R-Another way to write for loops

Screen Link:
Iterations In R — Another Way To Write For Loops | Dataquest

My Code:

millimeter_measurements <- c(10000, 54900, 94312, 49185, 2100)

for (i in indices) {calc<-millimeter_measurements[i]/1000

What I expected to happen:
numeric (double)
[1] 10

What actually happened:

numeric (double)
[1] 2.1
numeric (double)
[1] 10.000 54.900 94.312 49.185  2.100

Why were you expecting the above to happen?

because the first element in the given vector is 10000. Instead its giving the last element in the vector which is 2100. I apologize if I don’t make sense here. I am very new to R.

Nothing to apologize about! :slight_smile:

The i is defined and updated in the for loop. Once the for loop iterates through all the indices, i would have the last value in indices.

If you try to use i outside the for loop, it will use that last value.

That’s why meter_measurements[i] gives you 2.1 because outside the for loop, i would only have that last value from indices.

Let me know if that cleared things or not.

This explanation is so clear. Thank you!