I am trying to calculate the percent change between two points in R in the form of:
(X_(i+1) - X_(i))/(X_(i))
Here is what I have come up with so far:
#x is a vector from the dataframe
#lag is distance between two points being compared
percent_change = function(x,lag = 1)
{
n = length(x)
pchange = c((x[(1+lag):n] - x[1:(n-lag)])/x[1:(n-lag)],NA)
return(pchange)
}
However, in order to accomplish this task in R I had to bind an NA to avoid:
Error in \`$<-.data.frame\`(\`*tmp*\`, "Change", value = c(0.00248221082243916, :
replacement has 4616 rows, data has 4617
With this addition, the operation occurs and aligns to what I’ve calculate it should be on paper.
Is there a way where I do not have to append an NA?
You do need the
NAif you want to store thepc_changeresult back in the original data frame:Since the last element of your array does not have an
x+1to compare to it will produce a vector 1 (or lag) shorter than the original.Warning: Note that you have one
NAadded – this is correct for the caselag=1but more generally you need needlag×NAelements.Try replacing
NAwithrep(NA,lag).Here’s a more compact version of your function using the built-in
difffunction: