though I have found several similar questions, I could not find a simple solution to my problem in base R. I want to calculate the yoy percentage change from a set of data (here the y value) and add this "Delta"-series as a new column to my data frame.
For example:
>x = c(2000,2001,2002,2003,2004,2005,2006)
>y = c(100,104,106,108,112,115,121)
>df = data.frame(x,y)
And what to do if I load my data by reading a .csv file? Do i have to convert this data to a data frame?
data.table_1.9.5 introduced new function shift
, which by default will be type='lag'
and n=1L
. You could specify those arguments, if you need to change. setDT
converts data.frame
to data.table
, a new column is created (:=
) based on the criteria (y/shift(y)...
)
library(data.table)
setDT(df)[, new.col := y/shift(y) - 1]
Or in base R (from @David Arenburg's comments)
transform(df, new.col=c(NA,y[-1]/y[-nrow(df)]-1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With