I have a for loop that populates values into a data frame named Df. All my columns are populating accurately, but the following line of code does not produce that values that I want:
for(i in 2:(dim(Df)[1])){
Df$dailyReturns200[i] <- (Df$index200[i+1]-Df$index200[i])/Df$index200[i]
}
This is a simple return calculation of P2-P1/P1. A friend of mine has suggested an order of operations problem, but what is the solution?
Thank you!
Hard to answer without a reproducible example, but you shouldn’t need to do this in a loop at all. Does this do what you want?
From the help page,
diff()returns asuitably lagged and iterated differences.. In this case, all differences are one, and then are divided by x as shown above. See?difffor more details.