user3022875
user3022875

Reputation: 9018

dplyr or tidyr usage to transform table

I have this data frame

group = c("A","B","C")
num = c(1,2,3)
calc1 = c(4,5,6)
calc2 = c(7,8,9)
temp = c("GG","HH","KK")
temp2 = c("ll","pp","rr")
library(dplyr)
dat =data.frame(group = group, num = num , calc1 = calc1, calc2 = calc2, temp = temp, temp2 = temp2)
dat

  group num calc1 calc2 temp temp2
1     A   1     4     7   GG    ll
2     B   2     5     8   HH    pp
3     C   3     6     9   KK    rr

and I'd like to rearrange the data so the table looks like with a metric column that has num, calc1 and calc2 and the columnw with the value of group and removing the temp columns:

metric      A      B    C
num         1      2    3
calc1       4      5    6 
calc2       7      8    9

what's the best way to do that?

Upvotes: 0

Views: 49

Answers (1)

akuiper
akuiper

Reputation: 214957

Drop temp columns, gather and then spread:

library(dplyr); library(tidyr)

dat %>% 
    select(-starts_with('temp')) %>% 
    gather(metric, val, -group) %>% 
    spread(group, val)

#  metric A B C
#1  calc1 4 5 6
#2  calc2 7 8 9
#3    num 1 2 3

Upvotes: 4

Related Questions