2013-03-09 60 views
4

我有一个Date,并有兴趣将其表示为一个整数yyyymm窗体。目前,我这样做:R转换日期到月份表示

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 

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

回答

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 
+0

太棒了!看起来像'lubridate''月份'和'年份'功能比'base'快得多。使用'base'函数会大大增加时间。 – Alex 2013-03-10 00:16:53

0

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

function mydate(D) { 
    x <- replicate(dim(D)[0], get_year_month(..) 
    return(x) 
} 
+0

感谢您的回答。我不确定这意味着什么,不幸的是。你能否提供另外两个例子。 – Alex 2013-03-10 00:16:16

+0

嗨亚历克斯,请查看使用内置的“复制”,这将避免循环N次(N是您的数组中的条目数)的惩罚。 – javadba 2013-03-10 01:30:37

+0

'replicate'只是'lapply' ..仍然不知道你的意思。作为其他人与时间一起举例说明。这可能会消除一些混乱。 – Alex 2013-03-10 01:33:23

2

这将是最好的,让您的2012年新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

有点不熟悉'POSIXlt',但它看起来不像它提供相同的答案... – Alex 2013-03-09 23:18:43

+1

哎呀,我的坏。更正了我的答案。 '$ year'表示1900年后的年数,'$ mon'表示1月后的月数。详细信息'?POSIXlt'。 – 2013-03-09 23:56:26

2

您可以尝试使用zoo包中的yearmon类。一般来说,如果您正在进行时间序列操作和分析,我会建议使用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 
+0

(+1)承诺:) – Arun 2013-03-11 09:00:29

相关问题