I am working with a dataframe in R that is formatted like this sample:
Countries <- c('USA','USA','Australia','Australia')
Type <- c('a','b','a','b')
X2014 <- c(10, -20, 30, -40)
X2015 <- c(20, -40, 50, -10)
X2016 <- c(15, -10, 10, -100)
X2017 <- c(5, -5, 5, -10)
df_sample <- data.frame(Countries, Type, X2014, X2015, X2016, X2017)
The dataframe looks like this:
Countries Type X2014 X2015 X2016 X2017
1 USA a 10 20 15 5
2 USA b -20 -40 -10 -5
3 Australia a 30 50 10 5
4 Australia b -40 -10 -100 -10
I want to be able to create columns of year values for each type by each country, yielding something that looks like this:
Countries Year a b
1 USA X2014 10 -20
2 USA X2015 20 -40
3 USA X2016 15 -10
4 USA X2017 5 -5
...
With recast
I get this:
recast(df_sample, Countries ~ Type)
Countries a b
1 Australia 4 4
2 USA 4 4
With dcast
I get this:
dcast(df_sample, Countries ~ Type)
Countries a b
1 Australia 5 -10
2 USA 5 -5
The dataset I'm working with has 44 years of data, so I'd like to be able to indicate all columns of yearly data without having to enter each column id manually into a cast formula.
What is the difference between dcast
and recast
(i.e. what situations might they be best suited to), and is it possible to shape my data with them?