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
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
DFyou need to make your function return the newly modified data frame, and overwrite the old value ofDFwith it.To do this you add the line
return(DF)at the end of your function, and then call it withwhich results in
The reason that the columns
V2andV3are not equal is that there’s a bug in your original loop code: you have writtenDF[1,1]where you presumably intended to writeDF[i,1].