Search code examples
rtibbletidy

How to make operations with a tibble value based on a condition


I hope I can explain my problem, I have the following example:

    men <- c(204887,218530, 161706, 275769,159381, 184331, 166283,171636, 196118,
         189572, 157465,171137, 120363, 301591, 126385, 157317)
    women <- c(205113, 225793, 152857, 320207, 139366, 181088, 157010, 
         169101, 206268, 188374, 151218, 168920, 113733, 331912, 
         110329, 149641)
   age <-seq(27,42, by= 1)

which I made a tibble:

base1<-tibble(M=men, W=women, A=age)


   # A tibble: 16 x 3
        M      W     A
    <dbl>  <dbl> <dbl>
 1 204887 205113    27
 2 218530 225793    28
 3 161706 152857    29
 4 275769 320207    30.....

I want to be able to make operations like the next one in a simple way:

IR= (men_value at age 30)*5 / (men_val at age 28 + men_val at age 29 + ... + men_val at age 32)

I want to know which are the easiest ways without doing a buch of loops or conditions, hope you can help me, also I really want to do it using tibble because I'm gonna be working with databases, thanks in advance ! :)


Solution

  • A solution could look like the following.

    library(dplyr)
    library(magrittr)
    
    base1 <- structure(list(M = c(204887, 218530, 161706, 275769, 159381, 
    184331, 166283, 171636, 196118, 189572, 157465, 171137, 120363, 
    301591, 126385, 157317), W = c(205113, 225793, 152857, 320207, 
    139366, 181088, 157010, 169101, 206268, 188374, 151218, 168920, 
    113733, 331912, 110329, 149641), A = c(27, 28, 29, 30, 31, 32, 
    33, 34, 35, 36, 37, 38, 39, 40, 41, 42)), row.names = c(NA, -16L
    ), class = c("tbl_df", "tbl", "data.frame"))
    
    num <- base1 %>%
      filter(age == 30) %>%
      pull(M) %>%
      multiply_by(5)
    
    den <- base1 %>%
      filter(age %in% 28:32) %>%
      pull(M) %>%
      sum()
      
    num/den
    
    # [1] 1.379235