I was recently confronted to a situation that required going from a long dataset to a wide dataset, but with a small twist: there were two datasets, which I had to merge into one. You might wonder what kinda crappy twist that is, right? Well, let’s take a look at the data: data1; data2 ## # A tibble: 20 x 4 ## country date variable_1 value ## ## 1 lu 01/01/2005 maybe 22 ## 2 lu 01/07/2005 maybe 13 ## 3 lu 01/01/2006 maybe 40 ## 4 lu 01/07/2006 maybe 25 ## 5 lu 01/01/2005 totally_agree 42 ## 6 lu 01/07/2005 totally_agree 17 ## 7 lu 01/01/2006 totally_agree 25 ## 8 lu 01/07/2006 totally_agree 16 ## 9 lu 01/01/2005 totally_disagree 39 ## 10 lu 01/07/2005 totally_disagree 17 ## 11 lu 01/01/2006 totally_disagree 23 ## 12 lu 01/07/2006 totally_disagree 21 ## 13 lu 01/01/2005 kinda_disagree 69 ## 14 lu 01/07/2005 kinda_disagree 12 ## 15 lu 01/01/2006 kinda_disagree 10 ## 16 lu 01/07/2006 kinda_disagree 9 ## 17 lu 01/01/2005 kinda_agree 38 ## 18 lu 01/07/2005 kinda_agree 31 ## 19 lu 01/01/2006 kinda_agree 19 ## 20 lu 01/07/2006 kinda_agree 12 ## # A tibble: 20 x 4 ## country date variable_2 value ## ## 1 lu 01/01/2005 kinda_agree 22 ## 2 lu 01/07/2005 kinda_agree 13 ## 3 lu 01/01/2006 kinda_agree 40 ## 4 lu 01/07/2006 kinda_agree 25 ## 5 lu 01/01/2005 totally_agree 42 ## 6 lu 01/07/2005 totally_agree 17 ## 7 lu 01/01/2006 totally_agree 25 ## 8 lu 01/07/2006 totally_agree 16 ## 9 lu 01/01/2005 totally_disagree 39 ## 10 lu 01/07/2005 totally_disagree 17 ## 11 lu 01/01/2006 totally_disagree 23 ## 12 lu 01/07/2006 totally_disagree 21 ## 13 lu 01/01/2005 maybe 69 ## 14 lu 01/07/2005 maybe 12 ## 15 lu 01/01/2006 maybe 10 ## 16 lu 01/07/2006 maybe 9 ## 17 lu 01/01/2005 kinda_disagree 38 ## 18 lu 01/07/2005 kinda_disagree 31 ## 19 lu 01/01/2006 kinda_disagree 19 ## 20 lu 01/07/2006 kinda_disagree 12 As explained in Hadley (2014), this is how you should keep your data… But for a particular purpose, I had to transform these datasets.
var vglnk = { key: '949efb41171ac6ec1bf7f206d57e90b8' }; (function(d, t) { var s = d.createElement(t); s.type = 'text/javascript'; s.async = true; s.src = '//cdn.viglink.com/api/vglnk.js'; var r = d.getElementsByTagName(t)[0]; r.parentNode.insertBefore(s, r); }(document, 'script'));R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...