将日期转换为R中的年月代表

时间:2013-03-09 22:29:58

标签: r date posixct lubridate

我有Date,我有兴趣将其表示为yyyymm形式的整数。目前,我这样做:

get_year_month <- function(d) { return(as.integer(format(d, "%Y%m")))}
mydate = seq.Date(from=as.Date("2012-01-01"), to=as.Date("5012-01-01"), by=1) 
system.time(ym <- get_year_month(mydate))
#    user  system elapsed 
#    5.972   0.974   6.951 

这对于大型数据集来说非常慢。有更快的方法吗?请提供答案的时间安排,以便轻松比较。使用上面的例子。

4 个答案:

答案 0 :(得分:5)

使用lubridate包中的函数几乎是函数的两倍:

mydate = as.Date(rep("2012-01-01",1000))
library(lubridate)
library(microbenchmark)
microbenchmark(get_year_month(mydate),
               year(mydate)*100+month(mydate))

给出:

R> Unit: milliseconds
                               expr      min       lq   median       uq
             get_year_month(mydate) 2.150296 2.188370 2.218176 2.285973
 year(mydate) * 100 + month(mydate) 1.220016 1.228129 1.239704 1.284568

答案 1 :(得分:2)

如果您希望以这样的方式操作日期,最好将日期保持为POSIXlt格式:

> system.time(ym <- get_year_month(mydate))
   user  system elapsed 
  4.039   0.025   4.079 
> system.time(mydatep <- as.POSIXlt(mydate))
   user  system elapsed 
  3.576   0.016   3.603 
> system.time(ym <- (1900 + mydatep$year)*100 + (mydatep$mon + 1))
   user  system elapsed 
  0.010   0.005   0.015 

它仍然快一点,你可以免费获得随后的类似操作。

答案 2 :(得分:2)

您可以尝试使用yearmon包中的zoo类。一般来说,如果您正在进行时间序列操作和分析,我建议使用xts或至少zoo类。 xts具有很多用于分析非常大的时间序列数据的功能。

这是针对其他建议解决方案的快速基准。

get_year_month <- function(d) {
    return(as.integer(format(d, "%Y%m")))
}
mydate = as.Date(rep("2012-01-01", 1e+06))

microbenchmark(get_year_month(mydate), year(mydate) * 100 + month(mydate), as.yearmon(mydate, format = "%Y-%m-%d"), times = 1)
## Unit: milliseconds
##                                     expr       min        lq    median        uq       max neval
##                   get_year_month(mydate) 1049.8813 1049.8813 1049.8813 1049.8813 1049.8813     1
##       year(mydate) * 100 + month(mydate)  434.1765  434.1765  434.1765  434.1765  434.1765     1
##  as.yearmon(mydate, format = "%Y-%m-%d")  249.6704  249.6704  249.6704  249.6704  249.6704     1

答案 3 :(得分:0)

单个项目可能没有更快的方法。但是,通过使用内置复制,您可以使对集合进行操作的函数的版本比线性运行快得多。

function mydate(D) {
  x <- replicate(dim(D)[0], get_year_month(..)
  return(x)
}
相关问题