Home > Back-end >  How to use loop or other codes to get a ratio by divided first row in R?
How to use loop or other codes to get a ratio by divided first row in R?

Time:09-26

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

CodePudding user response:

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

CodePudding user response:

Just divide by respective row.

year[-1] <- year[-1] / as.vector(year[1, -1])
year
#   year pedal_cycles cars_and_taxis all_hgvs
# 1 1993     1.000000       1.000000 1.000000
# 2 1994     1.002294       1.020486 1.021430
# 3 1995     1.033583       1.038513 1.049010
# 4 1996     1.016751       1.064549 1.081607
# 5 1997     1.018537       1.081926 1.107183

Data:

year <- structure(list(year = 1993:1997, pedal_cycles = c(2489980831, 
2495693171, 2573600860, 2531689966, 2536137453), cars_and_taxis = c(210084884699, 
214388644505, 218175790767, 223645671968, 227296395346), all_hgvs = c(15071438165, 
15394423667, 15810086788, 16301368043, 16686840160)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))
  • Related