R set default origin for as.Date

烈酒焚心 提交于 2019-12-05 15:19:08

The zoo package adds a default origin:

library(zoo)

as.Date(0)
## [1] "1970-01-01"

There is an elegant and simple solution, like zoo, but allows for some tweaking if you need it:

require(anytime)

The base is simply:

anytime(0) which returns for me in eastern standard time:[1] "1969-12-31 19:00:00 EST"

If you want to be able to force it to the UTC center of the temporal universe

anytime(0, asUTC=TRUE)

which returns

[1] "1970-01-01 UTC"

And if you want to tell R that you your data is from a given time zone :

Sys.setenv(TZ= 'desiredTimeZone') with anytime:::getTZ() as your desired time zone if that is the one, in which, your dates were gathered.

Any of the answers will work, this one just gives you control over the integer (or string) of numerals as well as the time zone...so it is pretty universally useful if you are working with data gathered remotely.

The lubridate package has been specically made the work with dates easier :

library(lubridate)
as_date(0)
#[1] "1970-01-01"

Not really. There is no way the origin date can be changed and remain applicable forever in a session.

If you look at parameters for as.Date (i.e. function then origin does not has a default value when x is in numeric.

## S3 method for class 'numeric'
as.Date(x, origin, ...)

Perhaps, it would have been a good extension to as.Date function to provide default value for origin.

OP has done write thing to create a wrapper function to remove dependency on origin. Perhaps the function can be improved slightly like:

Modified function based on suggestions from suggestions from @sm1 and @Gregor.

## if date.origin is not defined then origin will be taken as "1970-01-01
options(date.origin = "1970-01-01")
as.date <- function(x, origin = getOption("date.origin")){
  origin <- ifelse(is.null(origin), "1970-01-01", origin)
  as.Date(x, origin)
}

## Results: (When date.origin is not set)
## > as.date(0)
## [1] "1970-01-01"
## > as.date(2)
## [1] "1970-01-03"
## Results: (When date.origin is set)
## > options(date.origin = "1970-01-05")
## > as.date(2)
## [1] "1970-01-07"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!