This may have already been answered but I could not find exactly what I wanted.
I have a data frame like:
Area <- c(1,1,1,1,2,2,2,2,3,3,3,3)
Scenario <- c(a,b,c,d,a,b,c,d,a,b,c,d)
Type <- c(EV, EV, EV, EV, EV, EV, EV, EV, EV, EV, EV, EV,)
Y2020 <- c(0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6)
Y2021 <- c(0.2,0.4,0.5,0.6,0.8,1.0,1.0,1.1,1.2,1.5,1.3,1.5)
y2022 <- c(0.3,0.6,0.2,0.7,0.5,0.6,0.7,0.8,0.9,1.1,1.3,1.6)
dt <- data.frame(Area,Scenario, Y2020, Y2021, Y2022)
So will look something like:
Area Scenario Type Y2020 Y2021 Y2022
1 a EV 0.5 0.2 0.3
1 b EV 0.6 0.4 0.6
1 c EV 0.7 0.5 0.8
1 d EV 0.8 0.6 0.7
2 a EV 0.9 0.8 0.5
2 b EV 1.0 1.0 0.6
2 c EV 1.1 1.0 0.7
2 d EV 1.2 1.1 0.8
3 a EV 1.3 1.2 0.9
3 b EV 1.4 1.5 1.1
3 c EV 1.5 1.3 1.3
3 d EV 1.6 1.5 1.6
I would like to get it in wide format by rotating by the Scenario column like this:
Area Type Y2020_a Y2021_a Y2022_a Y2020_b Y2021_b ...
1 EV 0.5 0.2 0.3 0.6 0.4
2 EV 0.9 0.8 0.5 1.0 1.0
3 EV 1.3 1.2 0.9 1.4 1.5
I tried to use dcast(dt, id ~ Scenario, value.var=names(dt)[4:6]) as suggested by @Arun from Reshape multiple values at once but it returned "Error in .subset2(x, i, exact = exact) : recursive indexing failed at level 2"
This is a condensed version of my actual data so if it could be replicated with a larger data set that would be great!
I hope someone can help! Thanks