dplyr 或 tidyr 用于转换 table

dplyr or tidyr usage to transform table

我有这个数据框

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

我想重新排列数据,使 table 看起来像一个包含 num、calc1 和 calc2 的度量列以及具有组值的 columnw 并删除临时列:

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

最好的方法是什么?

删除 temp 列,gather,然后 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