How do I use apply functions with a POSIXlt object?

Heyo,

I like to use a functional style, which can be a challenge. But I am trying to take an object Date

and get an arbitrary number of years ago.

# The Date object that is the starting point
referencedate <- as.Date("2015-06-30")
# The function that returns n years back
nYearsBack <- function(x,n){
  x <- as.POSIXlt(x)
  x$year <- x$year-n
  as.Date(x)
}
# The vector of years back we want returned as dates
yearsgoingback <- c(0,3,5)
# The function that doesn't work = (
datesgoingback <- sapply(X = yearsgoingback, FUN = function(x) nYearsBack(referencedate,x))

      

which returns

[1] 16616 15521 14790

      

To redo it, I have to run:

as.Date(datesgoingback, origin = "1970-01-01")

      

The question is, why would I need to take that one more step to convert an integer to an object Date

?

I thought it might be a simple, simple difference, but even when I run the above code with vapply

c FUN.VALUE = Sys.time()

then it gives the same integer result.

Is there a way to succinctly take a date (any kind that can be) and an arbitrary vector of integers and return a vector of years ago from the date you entered?

Thank you for your time.

+3


source to share





All Articles