【问题标题】:R Split series into monthR将系列拆分为月份
【发布时间】:2013-11-06 09:00:19
【问题描述】:

我有以下带有日期和计数的数据。请帮助转换这一行,其中月份是列。并且行是每年的数据

Date       count
=================  
2011-01-01 10578
2011-02-01  9330
2011-03-01 10686
2011-04-01 10260
2011-05-01 10032
2011-06-01  9762
2011-07-01 10308
2011-08-01  9966
2011-09-01 10146
2011-10-01 10218
2011-11-01  8826
2011-12-01  9504
to    
       JAN   FEB      MAR    APR   MAY  JUN   JUL  AUG  SEP    OCT NOV   DEC  
------------------------------------------------------------------------------
2011  10578   9330   10686 10260 10032 9762 10308 9966 10146 10218 8826 9504
2012 ....

【问题讨论】:

    标签: r time-series lubridate


    【解决方案1】:

    这是 R 基础中 ts 的完美任务。假设您的 data.frame 是 x然后使用 ts 将产生您想要的输出。

    > ts(x$count, start=c(2011,01,01), end=c(2011,12,01), frequency=12)
           Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
    2011 10578  9330 10686 10260 10032  9762 10308  9966 10146 10218  8826  9504
    

    【讨论】:

      【解决方案2】:

      如果您的数据在 x 中,请尝试以下操作:

      library(reshape2)
      res <- dcast(transform(x, month = format(Date, format="%m"),
                             year = format(Date, "%Y")),
                   year ~ month, value.var="count")
      rownames(res) <- res$year
      res <- res[,-1]
      names(res) <- toupper(month.abb[as.numeric(names(res))])
      res
      

      这假定x$Date 已经是一个日期。如果没有,您需要先将 is 转换为日期:

      x$Date <- as.Date(x$Date)
      

      【讨论】:

      • 数据被正确分割。但是几个月不合适。 ` 4 月 8 月 12 月 2 月 1 月 7 月 6 月 3 月 5 月 11 月 10 月 9 月` 2011 10260 9966 9504 9330 10578 10308 9762 10686 10032 8826 10218 10146
      • 我已经修复了,但我更喜欢ts 答案!
      猜你喜欢
      • 2019-12-05
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      相关资源
      最近更新 更多