Dplyr recast - variable not found

Firstly, here is the data tbl_df(simplified) that I use:

> mytbldf
Source: local data frame [6 x 5]

  iso2c country year     var1      var2
1    BI Burundi 2011 4.486265  6.693711
2    BI Burundi 2012 3.939242  5.330326
3    BI Burundi 2013 4.286439  5.747370
4    UG  Uganda 2011 3.998849 10.025680
5    UG  Uganda 2012 4.606198 13.416311
6    UG  Uganda 2013 4.746322 15.981362

I want to extend (in tidyr wording) the year variable to var1and var2. After some (...) iterations, I found a syntax that works:

> recast(mytbldf, iso2c + country ~ variable + year, measure.var = c("var1","var2"))
  iso2c country var1_2011 var1_2012 var1_2013 var2_2011 var2_2012 var2_2013
1    BI Burundi  4.486265  3.939242  4.286439  6.693711  5.330326   5.74737
2    UG  Uganda  3.998849  4.606198  4.746322 10.025680 13.416311  15.98136

Three questions:

1) if I do not specify measure.var =, I get the following error:

> recast(mytbldf, iso2c + country ~ variable + year)
Using iso2c, country as id variables
Error in eval(expr, envir, enclos) : object 'year' not found

Why? From a recastperson, I assumed that he would accept measure.varlike all other variables?

2) So, is there a way to avoid pointing measure.var? In my real case, there are too many variables with too long names to explicitly indicate them.

3) Is there a better / easier way to do this with reshape2or tidyr, which I am missing?

+4
1

devel data.table, value.var

library(data.table)#v1.9.5+
dcast(setDT(mytbldf), iso2c+country~year, value.var=c('var1', 'var2'))
#    iso2c country 2011_var1 2012_var1 2013_var1 2011_var2 2012_var2 2013_var2
#1:    BI Burundi  4.486265  3.939242  4.286439  6.693711  5.330326   5.74737
#2:    UG  Uganda  3.998849  4.606198  4.746322 10.025680 13.416311  15.98136

reshape base R

reshape(mytbldf, idvar=c('iso2c', 'country'), timevar='year', 
                 direction='wide')
#  iso2c country var1.2011 var2.2011 var1.2012 var2.2012 var1.2013 var2.2013
#1    BI Burundi  4.486265  6.693711  3.939242  5.330326  4.286439   5.74737
#4    UG  Uganda  3.998849 10.025680  4.606198 13.416311  4.746322  15.98136

recast melt + dcast. , id.var measure.var melt, long , . recast id.var

  library(reshape2)
  recast(mytbldf, id.var=c('iso2c', 'country', 'year'),
            iso2c+country~variable+year)
  #  iso2c country var1_2011 var1_2012 var1_2013 var2_2011 var2_2012 var2_2013
  #1    BI Burundi  4.486265  3.939242  4.286439  6.693711  5.330326   5.74737
  #2    UG  Uganda  3.998849  4.606198  4.746322 10.025680 13.416311  15.98136

, , , ,

 recast(mytbldf, measure.var=4:5,  iso2c+country~variable+year)
 #   iso2c country var1_2011 var1_2012 var1_2013 var2_2011 var2_2012 var2_2013
 #1    BI Burundi  4.486265  3.939242  4.286439  6.693711  5.330326   5.74737
 #2    UG  Uganda  3.998849  4.606198  4.746322 10.025680 13.416311  15.98136
+5

All Articles