Data wrangling for relative growth in % on yearly basis

How can we take the difference between the values on yearly basis ?
Please find the reprex below with an attempt to solve & :frowning:

library(tidyverse)
input = tribble(
  ~type,~val, ~year,
  "digital",10,   2000,
  "digital",20,   2001,
  "digital",30,   2002,
  "digital",15,   2003,
  "manual",50,    2000,
  "manual",25,   2001,
  "manual",100,  2002,
  "manual",50,  2003
)

# Basically relative growth on yearly basis for each combination
output <- tribble(
  ~type,~rel_val_per, ~year,
  "digital",100,   2001,
  "digital",100,   2002,
  "digital",50,   2003,
  "manual",50,    2000,
  "manual",25,   2001,
  "manual",100,  2002,
  "manual",50,  2003
)

# tried
# 
# x %>% 
#   gather(-type, key = key, value = val) %>%
#   group_by(type) %>% 
#   mutate(relval = diff(val))

In your topic's title you are talking about relative growth in percentage, so is this what you want?

library(tidyverse)
input <- tribble(
    ~type,~val, ~year,
    "digital",10,   2000,
    "digital",20,   2001,
    "digital",30,   2002,
    "digital",15,   2003,
    "manual",50,    2000,
    "manual",25,   2001,
    "manual",100,  2002,
    "manual",50,  2003
)

input %>% 
    group_by(type) %>% 
    arrange(type, year) %>% 
    mutate(relval = (val - lag(val))/lag(val))
#> # A tibble: 8 x 4
#> # Groups:   type [2]
#>   type      val  year relval
#>   <chr>   <dbl> <dbl>  <dbl>
#> 1 digital    10  2000   NA  
#> 2 digital    20  2001    1  
#> 3 digital    30  2002    0.5
#> 4 digital    15  2003   -0.5
#> 5 manual     50  2000   NA  
#> 6 manual     25  2001   -0.5
#> 7 manual    100  2002    3  
#> 8 manual     50  2003   -0.5

Created on 2019-07-23 by the reprex package (v0.3.0.9000)
If it's not, then please provide an example of your desired output and try to explain what are you trying to do with your code.

3 Likes

Thanks @andresrcs, This is exactly I was looking for.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.