Calculate percent change from one vector (x) to another (y)
pct_change(x, y, denominator = 100)
x | [ |
---|---|
y | [ |
denominator | [ |
[numeric()
]
Percent change from x to y: denominator * (y - x) / x
#> [1] 900 100 50# data.table library(data.table) dt <- data.table( x = c(10, 11, 12), y = c(100, 22, 18) ) dt[, change := pct_change(x, y)]#> x y change #> 1: 10 100 900 #> 2: 11 22 100 #> 3: 12 18 50# percent change within one data.table column dt <- data.table( year = c(2000, 2001, 2002), val = c(10, 11, 12) ) dt[, change := pct_change(x = shift(val), y = val)]#> year val change #> 1: 2000 10 NA #> 2: 2001 11 10.000000 #> 3: 2002 12 9.090909