R重塑数据框

时间:2014-09-15 13:23:30

标签: r reshape

我有一个数据框ema_sma_actual,如下所述,

fiscal_quarter     actual    forecast_ema forecast_sma
         20071  6371428347           NA           NA
         20072  4370623177           NA           NA
         20073  3377139334    5056396953    5063969536
         20074  8380921297    6953659125    5762279366
         20081  7315765174    7054712149    6579419356
         20082 11325882146    9155297148    9075228726
         20083  6311248678    7653272913    8176319996

我希望将其转换为

 type               Amount              fiscal_quarter
        actual    6371428347          20071
  forecast_ema         NA             20071
  forecast_sma         NA             20071
        actual    3377139334          20072
  forecast_ema    5056396953          20072
  forecast_sma    5063969536          20072
        actual    8380921297          20073
  forecast_ema    6953659125          20073
  forecast_sma    5762279366          20073
       actual    7315765174          20074
 forecast_ema    7054712149          20074
 forecast_sma    6579419356          20074
       actual   11325882146          20081
 forecast_ema    9155297148          20081
 forecast_sma    9075228726          20081
       actual    6311248678          20082
 forecast_ema    7653272913          20082
 forecast_sma    8176319996          20082
       actual    7356638637          20083
 forecast_ema    7559955775          20083
 forecast_sma    8312564876          20083

我该怎么做?

1 个答案:

答案 0 :(得分:1)

tidyr解决方案

df<-read.table(text="fiscal_quarter     actual    forecast_ema forecast_sma
20071  6371428347           NA           NA
20072  4370623177           NA           NA
20073  3377139334    5056396953    5063969536
20074  8380921297    6953659125    5762279366
20081  7315765174    7054712149    6579419356
20082 11325882146    9155297148    9075228726
20083  6311248678    7653272913    8176319996", header=T)


library(tidyr) 
library(dplyr)

df %>% gather(key,amount, 2:4)

如果您希望它符合上述顺序,您可以添加:

df %>% 
   gather(key,amount, 2:4) %>%
   arrange(fiscal_quarter, key)