将data.frame从宽格式重塑为长格式[其他示例没有帮助]

时间:2018-03-09 17:52:17

标签: r

将data.frame从宽表转换为长表时遇到了一些麻烦。目前它看起来像这样:

Data Frame

我查看过诸如[melt]和[reshape]之类的命令,但是无法转换表格。 我需要它像这样

Monat   Value
2008-01  849
2008-02  771
2008-03  822
.
.
2015-12  719

Data frame should be presented like this

我尝试了以下代码,但它不起作用:

reshape(SuicideTable, direction = "long", varying = list(names(SuicideTable)[13:9]), v.names = "Value", 
        idvar = c("Monat"), timevar = "Value1", times = 2008:2015)

1 个答案:

答案 0 :(得分:3)

您可以使用gatherunite

  library(dplyr)
  library(tidyr)

  # example data
  mat <- (matrix(rnorm(12*8, mean = 800, sd = 200), nrow = 12))
  df <- data.frame(months = month.abb, mat)
  colnames(df)[-1] <- 2008:2015

  #    months     2008      2009      2010     2011     2012      2013  ...    
  # 1     Jan 578.1627 1005.3642  622.2480 738.3829 448.1257 1112.2660  
  # 2     Feb 950.1085  857.4998  866.0585 629.5612 848.3288  714.2643  
  # 3     Mar 650.0593  852.8997  797.3760 719.5924 696.3195  793.7964  
  # ...

  df %>% gather(year, Value, - months) %>% 
       unite(Month, year, months, sep = "-")

 #       Month     Value
 # 1  2008-Jan  578.1627
 # 2  2008-Feb  950.1085
 # 3  2008-Mar  650.0593
 # 4  2008-Apr  590.9742
 # 5  2008-May  671.8589
 # 6  2008-Jun  829.1035
 # 7  2008-Jul  755.9633
 # 8  2008-Aug  824.7879
 # ...

如果您希望将月份表示为数字,并且您知道您的数据集与图片中的数据顺序相同,则可以mutate将该变量表示为1:12的数字

   library(stringr)

   df %>% mutate(months = str_pad(1:12, 2,pad = "0")) %>%
          gather(year, Value, - months) %>% 
          unite(Month, year, months, sep = "-")

   #      Month     Value
   # 1  2008-01  578.1627
   # 2  2008-02  950.1085
   # 3  2008-03  650.0593
   # 4  2008-04  590.9742
   # 5  2008-05  671.8589
   # 6  2008-06  829.1035
   # ...