I'm new to R (and programming generally), and confused about why the following bits of code yield different results:
x <- 100
for(i in 1:5){
x <- x + 1
print(x)
}
This incrementally prints the sequence 101:105 as I would expect.
x <- 100
f <- function(){
x <- x + 1
print(x)
}
for(i in 1:5){
f()
}
But this just prints 101 five times.
Why does packaging the logic into a function cause it to revert to the original value on each iteration rather than incrementing? And what can I do to make this work as a repeatedly-called function?
For loop in R Programming Language is useful to iterate over the elements of a list, dataframe, vector, matrix, or any other object. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object.
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.
for() is one of the most popular functions in R. As you know, it is used to create loops. For example, let's calculate squared values for 1 to 3. It is very easy.
It is because in your function you are dealing with a local variable x
on the left side, and a global variable x
on the right side. You are not updating the global x
in the function, but assigning the value of 101
to the local x
. Each time you call the function, the same thing happens, so you assign local x
to be 101
5 times, and print it out 5 times.
To help visualize:
# this is the "global" scope
x <- 100
f <- function(){
# Get the "global" x which has value 100,
# add 1 to it, and store it in a new variable x.
x <- x + 1
# The new x has a value of 101
print(x)
}
This would be similar to the following code:
y <- 100
f <- function(){
x <- y + 1
print(x)
}
As for what to do to fix it. Take the variable as the argument, and pass it back as the update. Something like this:
f <- function(old.x) {
new.x <- old.x + 1
print(new.x)
return(new.x)
}
You would want to store the return value, so your updated code would look like:
x <- 100
f <- function(old.x) {
new.x <- old.x + 1
print(new.x)
return(new.x)
}
for (i in 1:5) {
x <- f(x)
}
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