通过将列名称拖放到新列中来重塑数据表

时间:2018-03-21 11:11:18

标签: r data.table

早上好,

我决定给R一个关于我通常在Excel上执行的任务的尝试,但是由于表的大小,计算机拒绝工作。通常,我遵循here所述的程序。

简而言之,我想转换一下:

dt <- data.table(name = c("Jack", "Gill", "Tom", "Jerry"), Math = c(55,65,75,85), History = c(50,60,70,80), Geography = c(55,66,77,88))

        Math    History   Geography
Jack    55      50        55
Gill    65      60        66
Tom     75      70        80
Jerry   85      80        88

进入这个:

Jack   Math       55
Jack   History    50
Jack   Geography  55
Gill   Math       65
Gill   History    60
Gill   Geography  66
Tom    Math       75
Tom    History    70
Tom    Geography  77
Jerry  Math       85
Jerry  History    80
Jerry  Geography  88

任何建议都非常感谢:)

修改:重复。谢谢你,akrun指出我正确的方向!

1 个答案:

答案 0 :(得分:3)

library(tidyverse)

dt <- data.frame(name = c("Jack", "Gill", "Tom", "Jerry"), Math = c(55,65,75,85), History = c(50,60,70,80), Geography = c(55,66,77,88))

dt %>% 
  gather(subjects, score, -name) %>% 
  arrange(name)

    name  subjects    score
1   Gill      Math       65
2   Gill   History       60
3   Gill Geography       66
4   Jack      Math       55
5   Jack   History       50
6   Jack Geography       55
7  Jerry      Math       85
8  Jerry   History       80
9  Jerry Geography       88
10   Tom      Math       75
11   Tom   History       70
12   Tom Geography       77