Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading