I'm tyring to build a function in R which calculates the percentage change between rows based on any arbitrary index, this is, between any given row and the preceding one or any given row and n preceding ones.
perc_change <- function(x,n) {
y <- c()
z <- c()
for (i in 1:length(x)) {
z[i] <- (x[i]/(x[i-n])-1)*100
}
y <- c(rep(NA,n),z[(n+1):length(z)])
y
}
When n is one the function works properly:
x <- c(2,3.5,4,6)
perc_change(x,1)
[1] NA 75.00000 14.28571 50.00000
But when I change to 2 or other n, I receive this error:
Error in z[i] <- (x[i]/(x[i - n]) - 1) * 100 :
replacement has length zero
I just can't find why and where the logic of my function is wrong so I appreciate any comment or suggestion.