重塑数据帧

时间:2016-11-29 16:59:11

标签: r casting dplyr reshape

我有一个数据框:

Family <- c('A','B','C', 'D', 'E', 'F', 'G', 'H', 'I', 'J')
This_Month <- c(1000, 2000, 3000, 4000, 5000, 6000,7000,8000,9000,10000)
Last_Month <- c(11000, 12000, 13000, 14000, 15000, 16000,17000,18000,19000,20000)

df1 <- data.frame(Family, This_Month, Last_Month)

   Family    This_Month   Last_Month
1       A          1000        11000
2       B          2000        12000
3       C          3000        13000
4       D          4000        14000
5       E          5000        15000
6       F          6000        16000
7       G          7000        17000
8       H          8000        18000
9       I          9000        19000
10      J         10000        20000

如何重塑这个以便它变成下面的数据帧。我想取列This_MonthLast_Month并将其转换为行值及其相应的数字。

      Date        Family    Revenue
This_Month             A       1000
Last_Month             A      11000
This_Month             B       2000
Last_Month             B      12000
This_Month             C       3000
Last_Month             C      13000
This_Month             D       4000
Last_Month             D      14000
This_Month             E       5000
Last_Month             E      15000
This_Month             F       6000
Last_Month             F      16000
This_Month             G       7000
Last_Month             G      17000
This_Month             H       8000
Last_Month             H      18000
This_Month             I       9000
Last_Month             I      19000
This_Month             J      10000
Last_Month             J      20000

谢谢!

2 个答案:

答案 0 :(得分:1)

只需使用令人惊叹的tidyverse,特别是gather()功能。

library(tidyverse)

df2 <- df1 %>%
 gather(variable, value, -Family)

答案 1 :(得分:1)

您可以使用包melt中的reshape2

> library('reshape2')
> melt(df1, id='Family', variable.name='Date')
    Family       Date value
1       A This_Month  1000
2       B This_Month  2000
3       C This_Month  3000
4       D This_Month  4000
5       E This_Month  5000
6       F This_Month  6000
7       G This_Month  7000
8       H This_Month  8000
9       I This_Month  9000
10      J This_Month 10000
11      A Last_Month 11000
12      B Last_Month 12000
13      C Last_Month 13000
14      D Last_Month 14000
15      E Last_Month 15000
16      F Last_Month 16000
17      G Last_Month 17000
18      H Last_Month 18000
19      I Last_Month 19000
20      J Last_Month 20000
相关问题