Calculate percent change from one vector (x) to another (y)

pct_change(x, y, denominator = 100)

Arguments

x

[numeric()]
Baseline value(s)

y

[numeric()]
Comparison value(s)

denominator

[numeric()]
Default to 100 for percent (ex: 20%). Specify denominator = 1 to get percent change as a decimal (ex: 0.20).

Value

[numeric()]
Percent change from x to y: denominator * (y - x) / x

Examples

# vectors pct_change(x = c(10, 11, 12), y = c(100, 22, 18))
#> [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