compute variable over the value of the difference between another variable this year and the previous one R

In the data below I want to compute the following ratio tr(year)/(op(year) – op(year-1). I would appreciate an answer with dplyr.

year     op    tr    cp
  <chr> <dbl> <dbl> <dbl>
1 1984     10  39.1  38.3
2 1985     55 132.   77.1
3 1986     79  69.3  78.7
4 1987     78  47.7  74.1
5 1988    109  77.0  86.4

this is the expected output


year2          ratio
1  1985   2.933333
2  1986   2.887500
3  1987 -47.700000
4  1988  -2.483871

I do not manage to get to any result…

>Solution :

Use lag:

library(dplyr)
df %>% 
  mutate(year = year,
         ratio = tr / (op - lag(op)),
         .keep = "none") %>% 
  tidyr::drop_na()

#  year      ratio
#2 1985   2.933333
#3 1986   2.887500
#4 1987 -47.700000
#5 1988   2.483871

Leave a Reply