0

I have a long-form dataframe in the following format:

data.frame(id = rep(1:3, each = 3), category = rep(c("a","b","c"),3),
                      qtr_1 = rpois(9,1),qtr_2 = rpois(9,1),
                      qtr_3 = rpois(9,1),qtr_4 = rpois(9,1))


id category qtr_1 qtr_2 qtr_3 qtr_4
 1    a       2     0    0      1
 1    b       2     1    2      1
 1    c       3     2    0      0
 2    a       1     0    1      0 
 2    b       1     3    1      0 
 3    c       1     0    1      1 

I am trying to combine the category and "qtr_#" columns such that I have a dataframe with 4 columns for each category (category + qtr) and a single row for each id. The desired end result of the columns would look like:

id qtr_1.a qtr_2.a qtr_3.a qtr_4.a qtr_1.b qtr_2.b qtr_3.b qtr_4.b ....

I'm certain there's a way with a combination of tidyr or reshape2, but I am driving myself nuts trying to work it out.

Gio Circo
  • 332
  • 2
  • 9
  • 2
    require(tidyverse) df<-data.frame(id = rep(1:3, each = 3), category = rep(c("a","b","c"),3), qtr_1 = rpois(9,1),qtr_2 = rpois(9,1), qtr_3 = rpois(9,1),qtr_4 = rpois(9,1)) df %>% gather(quarter, Value, matches("qtr")) %>% unite(qtr_ctgry, quarter, category, sep = ".") %>% spread(qtr_ctgry, Value) – Zafar May 05 '17 at 17:48
  • 1
    You have to finish making the data long before spreading it to wide format. So, in `tidyr` world, `gather`, make the id you want to use as column names in the final product, then `spread`. – ulfelder May 05 '17 at 17:51
  • Dan: This is precisely what I was looking for. If you post your comment as an answer I'll accept it. – Gio Circo May 05 '17 at 17:57

0 Answers0