Skip to content

Instantly share code, notes, and snippets.

@sckott
Created October 19, 2016 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sckott/30aa76eb3d298d22aa231d72f1d0e474 to your computer and use it in GitHub Desktop.
Save sckott/30aa76eb3d298d22aa231d72f1d0e474 to your computer and use it in GitHub Desktop.

one solution

library(tidyr)

df <- data.frame(
  foo_m_aaa = 1:3,
  foo_m_bbb = 1:3,
  foo_f_aaa = 1:3,
  foo_f_bbb = 1:3,
  bar_m_aaa = 1:3,
  bar_m_bbb = 1:3,
  bar_f_aaa = 1:3,
  bar_f_bbb = 1:3
)

gather(df, key = type, value = score) %>% 
  separate(col = type, into = c('type', 'gender', 'thing'))

gives

   type gender thing score
1   foo      m   aaa     1
2   foo      m   aaa     2
3   foo      m   aaa     3
4   foo      m   bbb     1
5   foo      m   bbb     2
6   foo      m   bbb     3
7   foo      f   aaa     1
8   foo      f   aaa     2
9   foo      f   aaa     3
10  foo      f   bbb     1
11  foo      f   bbb     2
12  foo      f   bbb     3
13  bar      m   aaa     1
14  bar      m   aaa     2
15  bar      m   aaa     3
16  bar      m   bbb     1
17  bar      m   bbb     2
18  bar      m   bbb     3
19  bar      f   aaa     1
20  bar      f   aaa     2
21  bar      f   aaa     3
22  bar      f   bbb     1
23  bar      f   bbb     2
24  bar      f   bbb     3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment