2016-11-29 115 views
1

我有一個數據幀這樣:重塑數據幀

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 

謝謝!

回答

1

只是利用了驚人的tidyverse,特別是gather()函數。

library(tidyverse) 

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

完美,謝謝! @boshek –

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