Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

year-over-year percentage change in R

Tags:

r

time-series

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?

like image 887
Gilles Cosyn Avatar asked Feb 11 '23 03:02

Gilles Cosyn


1 Answers

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))
like image 62
akrun Avatar answered Feb 13 '23 17:02

akrun