Deuian
Deuian

Reputation: 841

Loop to add extra column works but not when in a function

I have a loop that works but not when I try and use it in a function. The below shows the data frame before and after the loops

DF

  MSU
1  12
2  11
3   6
4   5
5   6
6   6

Loop

for (i in 1:nrow(DF)) 
{  
    if(i<4) { DF[ i, 2 ] <- 0} else 
    {
        DF[ i, 2 ] <- ((DF[1,1] + DF[i-1,1] + DF[i-2,1] + DF[i-3,1])/4) 
    }
}

DF after loop, an extra column has been added with the average of the last four values unless the number of values was less than four.

  MSU    V2
1  12  0.00
2  11  0.00
3   6  0.00
4   5 10.25
5   6  8.50
6   6  7.25

Function with Loop

myfct <- function(DF){
for (i in 1:nrow(DF)) 
{  
    if(i<4) { DF[ i, 3 ] <- 0} else 
    {
        DF[ i, 3 ] <- ((DF[i,1] + DF[i-1,1] + DF[i-2,1] + DF[i-3,1])/4) 
    }
}
}

DF after function with Loop, there should ba an extra column with the same values as column 2 but it is not added. I have used print to show that the loop is being executed and the values are what I expect to put in the 3rd column.

  MSU    V2
1  12  0.00
2  11  0.00
3   6  0.00
4   5 10.25
5   6  8.50
6   6  7.25

Upvotes: 0

Views: 631

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 47392

R passes arguments by value, not by reference. This means that when you pass an object into a function, R creates a local copy of the object. Any changes you make to the object inside the function affect only the local copy, and not the original.

To modify DF you need to make your function return the newly modified data frame, and overwrite the old value of DF with it.

To do this you add the line return(DF) at the end of your function, and then call it with

DF <- myfct(DF)

which results in

> DF
  MSU    V2   V3
1  12  0.00 0.00
2  11  0.00 0.00
3   6  0.00 0.00
4   5 10.25 8.50
5   6  8.50 7.00
6   6  7.25 5.75

The reason that the columns V2 and V3 are not equal is that there's a bug in your original loop code: you have written DF[1,1] where you presumably intended to write DF[i,1].

Upvotes: 3

Related Questions