4
$\begingroup$

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?

$\endgroup$

1 Answer 1

2
$\begingroup$

See ?reshape2::recast: The function

conveniently wraps melting and (d)casting a data frame into a single step.

library(reshape2)
recast(df_sample, Countries+variable~Type, id.var=1:2)
#   Countries variable  a    b
# 1 Australia    X2014 30  -40
# 2 Australia    X2015 50  -10
# 3 Australia    X2016 10 -100
# 4 Australia    X2017  5  -10
# 5       USA    X2014 10  -20
# 6       USA    X2015 20  -40
# 7       USA    X2016 15  -10
# 8       USA    X2017  5   -5

So, it's just a shortcut for these two steps:

(tmp <- melt(df_sample, id.vars=1:2))
#    Countries Type variable value
# 1        USA    a    X2014    10
# 2        USA    b    X2014   -20
# 3  Australia    a    X2014    30
# 4  Australia    b    X2014   -40
# 5        USA    a    X2015    20
# ...
dcast(tmp, Countries+variable~Type)
#   Countries variable  a    b
# 1 Australia    X2014 30  -40
# 2 Australia    X2015 50  -10
# 3 Australia    X2016 10 -100
# 4 Australia    X2017  5  -10
# 5       USA    X2014 10  -20
# 6       USA    X2015 20  -40
# 7       USA    X2016 15  -10
# 8       USA    X2017  5   -5
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.