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

How to use loop or other codes to get a ratio by divided first row in R?

I have a data frame called year

    year pedal_cycles cars_and_taxis     all_hgvs
   <int>        <dbl>          <dbl>        <dbl>
 1  1993  2489980831.  210084884699. 15071438165.
 2  1994  2495693171.  214388644505. 15394423667.
 3  1995  2573600860.  218175790767. 15810086788.
 4  1996  2531689966.  223645671968. 16301368043.
 5  1997  2536137453.  227296395346. 16686840160.

I want to get ratios relative to the first row (year==1993), I used the following lines, and I wonder if I could use loop or other ways to achieve it.

year %>%
  mutate (
    pedal_cycles = pedal_cycles/pedal_cycles[year==1993], 
    cars_and_taxis = cars_and_taxis/cars_and_taxis[year==1993],
    all_hgvs = all_hgvs/all_hgvs [year==1993]
    ) 
    year pedal_cycles cars_and_taxis all_hgvs
   <int>        <dbl>          <dbl>    <dbl>
 1  1993        1               1        1   
 2  1994        1.00            1.02     1.02
 3  1995        1.03            1.04     1.05
 4  1996        1.02            1.06     1.08
 5  1997        1.02            1.08     1.11

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 :

library(tidyverse) 

df %>%  
  mutate(across(2:4, ~ .x / first(.x)))

# A tibble: 5 x 4
   year pedal_cycles cars_and_taxis all_hgvs
  <dbl>        <dbl>          <dbl>    <dbl>
1  1993         1              1        1   
2  1994         1.00           1.02     1.02
3  1995         1.03           1.04     1.05
4  1996         1.02           1.06     1.08
5  1997         1.02           1.08     1.11
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