Please consider an reprex below:
Can we arrive at the expected output without manually creating intermediate column names via summarise and mutate ?
library(tidyverse)
# Input data
data = data.frame(
season = c("SU","SU","WI","WI"),
farmer = c("A","B","A","B"),
"2013" = c(25,20,22,10),
"2014" = c(56,40,100,90),
"2015" = c(60,30,160,80),
"2016" = c(90,60,120,50),
"2017" = c(52,20,62,10),
"2018" = c(5,2,29,10)
)
# Can we arrive at this output without manual naming the column names ?
# e.g. each summarise and mutate has a manually named column names
# Can we make it auto-generated ?
expected_output = data %>%
gather(key = key, value = value,
("X2013":"X2018")) %>%
mutate(farmer_year = paste(farmer,key),
key = NULL,
value = value %>% as.integer()) %>%
spread(farmer_year, value) %>%
group_by(season) %>%
summarise(`A X2013` = sum(`A X2013` %>% as.integer(), na.rm = T),
`B X2013` = sum(`B X2013` %>% as.integer(),na.rm = T),
`A X2014` = sum(`A X2014` %>% as.integer(), na.rm = T),
`B X2014` = sum(`B X2014` %>% as.integer(), na.rm = T),
`A X2015` = sum(`A X2015` %>% as.integer(), na.rm = T),
`B X2015` = sum(`B X2015` %>% as.integer(), na.rm = T),
`A X2016` = sum(`A X2016` %>% as.integer(), na.rm = T),
`B X2016` = sum(`B X2016` %>% as.integer(), na.rm = T),
`A X2017` = sum(`A X2017` %>% as.integer(), na.rm = T),
`B X2017` = sum(`B X2017` %>% as.integer(), na.rm = T),
`A X2018` = sum(`A X2018` %>% as.integer(), na.rm = T),
`B X2018` = sum(`B X2018` %>% as.integer(), na.rm = T)) %>%
mutate(ratio_2013 = 100*`B X2013`/`A X2013`,
farmer_growth_2014 = 100*`A X2014`/`A X2013`,
ratio_2014 = 100*`B X2014`/`A X2014`,
ratio_diff_13_14 = ratio_2014 - ratio_2013,
farmer_growth_2015 = 100*`A X2015`/`A X2014`,
ratio_2015 = 100*`B X2015`/`A X2015`,
ratio_diff_14_15 = ratio_2015 - ratio_2014,
farmer_growth_2016 = 100*`A X2016`/`A X2015`,
ratio_2016 = 100*`B X2016`/`A X2016`,
ratio_diff_15_16 = ratio_2016 - ratio_2015,
farmer_growth_2017 = 100*`A X2017`/`A X2016`,
ratio_2017 = 100* `B X2017`/`A X2017`,
ratio_diff_16_17 = ratio_2017 - ratio_2016,
farmer_growth_2018 = 100*`A X2018`/`A X2017`,
ratio_2018 = 100*`B X2018`/`A X2018`,
ratio_diff_17_18 = ratio_2018 - ratio_2017)