R set default origin for as.Date

房东的猫 提交于 2019-12-07 12:25:45

问题


Is there a way to set default origin for as.Date? I did this function to workaround:

as.date=function(x, origin='1970-01-01') as.Date(x, origin=origin)

For example:

as.Date(0)
Error in as.Date.numeric(0) : 'origin' deve ser especificado

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

回答1:


The zoo package adds a default origin:

library(zoo)

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



回答2:


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.




回答3:


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

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



回答4:


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"


来源:https://stackoverflow.com/questions/48241567/r-set-default-origin-for-as-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!