Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop on R function

Tags:

r

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?

like image 602
mmk Avatar asked May 18 '13 14:05

mmk


People also ask

Can I put a for loop in a function in R?

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.

What is the function of for loop?

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.

What is the for function in R?

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.


1 Answers

The problem

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)
}

One possible fix

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)
}
like image 130
joneshf Avatar answered Sep 27 '22 21:09

joneshf