将日期转换为年份月份的形式

问题描述 投票:5回答:4

我有一个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 

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

r date posixct lubridate
4个回答
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

3
投票

您可以尝试使用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

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 

它仍然快一点,并且在时间上您可以免费获得随后的类似操作。


0
投票

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

function mydate(D) {
  x <- replicate(dim(D)[0], get_year_month(..)
  return(x)
}
© www.soinside.com 2019 - 2024. All rights reserved.