R for loop counter variable remains in global environment

921 Views Asked by At

In R, why does the j variable defined in the below for-loop remain in the global environment/scope after the loop execution.

for (j in 1:2){
  print(j)
}

Screenshot of terminal window with code execution where you see the variables in the global environment before and after the for loop execution.

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

It is a design choice. If you look at the documentation

?`for`

It says

When the loop terminates, var remains as a variable containing its latest value.

I expect that is so that if you jump out of the loop, say with last() you can know which index you were on.