Ale*_*lex 4 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
Run Code Online (Sandbox Code Playgroud)
这对于大型数据集来说非常慢.有更快的方法吗?请提供答案的时间安排,以便轻松比较.使用上面的例子.
使用lubridate包中的函数几乎可以是函数的两倍:
mydate = as.Date(rep("2012-01-01",1000))
library(lubridate)
library(microbenchmark)
microbenchmark(get_year_month(mydate),
year(mydate)*100+month(mydate))
Run Code Online (Sandbox Code Playgroud)
给出:
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
Run Code Online (Sandbox Code Playgroud)