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)
meter_measurements<-integer(length(millimeter_measurements))
indices<-1:length(millimeter_measurements)

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

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

What actually happened:

meter_measurements[i]
numeric (double)
[1] 2.1
meter_measurements
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!