I would like to calculate growth rates across rows by groups (here groups are "country" and "year") in a dataset that is in the long format. Since the growth rate should be relative to the same value (i.e., same "country" and same "year") under the "Baseline" scenario (not relative to the previous row), I am doing this by changing the data format to wide format, as follows:
df <- spread(df, scenario, value) %>%
mutate(NDC_growth=((NDC/Baseline)-1)*100,
`Partial BCA_growth`=((`Partial BCA`/Baseline)-1)*100,
BCA_growth=((BCA/Baseline)-1)*100,
`Full BCA_growth`=((`Full BCA`/Baseline)-1)*100 )
Is there a way to do it in the long format?
Here is the data:
df<- structure(list(country = c("CAN", "CAN", "CAN", "CAN", "CAN",
"CAN", "CAN", "CAN", "CAN", "CAN", "CAN", "CAN", "CAN", "CAN",
"CAN", "NCOA", "NCOA", "NCOA", "NCOA", "NCOA"), year = c("2020",
"2020", "2020", "2020", "2020", "2025", "2025", "2025", "2025",
"2025", "2030", "2030", "2030", "2030", "2030", "2020", "2020",
"2020", "2020", "2020"), scenario = c("Baseline", "BCA", "Full BCA",
"NDC", "Partial BCA", "Baseline", "BCA", "Full BCA", "NDC", "Partial BCA",
"Baseline", "BCA", "Full BCA", "NDC", "Partial BCA", "Baseline",
"BCA", "Full BCA", "NDC", "Partial BCA"), value = c(50527.8708215592,
50487.4619290311, 50485.0924261504, 50489.4453487844, 50486.1975947164,
55845.9708589775, 55070.2745559464, 55133.107605613, 55153.4525662034,
55065.0036253937, 61463.2383809614, 59893.8712077455, 59971.8726308887,
59936.72156767, 59875.7762254252, 338418.917408225, 338420.617142445,
338428.007621131, 338419.514027857, 338427.263672463)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))