R set the default value for as.Date

Is there a way to set the default value for as.Date? I made this function to work around:

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

For instance:

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

as.date(0)
[1] "1970-01-01"
+4
source share
4 answers

The zoo package adds a default beginning:

library(zoo)

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

There is an elegant and simple solution, such as a zoo, but if necessary, you can customize it:

require(anytime)

The base is simple:

anytime(0) which returns to me at Eastern Standard Time: [1] "1969-12-31 19:00:00 EST"

If you want him to be able to force redirect it to the UTC center of the temporary universe

anytime(0, asUTC=TRUE)

which returns

[1] "1970-01-01 UTC"

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

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

, ( ) , ... , .

+4

. origin .

as.Date (.. , origin , x numeric.

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

, as.Date, default origin.

OP , -, origin. , , :

, @sm1 @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"
+2
source

The package has lubridatebeen specially facilitated for working with dates:

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

Source: https://habr.com/ru/post/1692139/


All Articles