0

Here is the reproductible example (at least on my computer)

a <- as.Date(as.Date("2012-10-01"):as.Date("2013-03-25"))
myFun <- function (x) {
    return(sqrt(abs(as.numeric(x-as.Date("2013-01-01")))))
}

for (i in 1:length(a)) { print(myFun(a[i])) } works fine but

sapply(a,myFun) fails with error message

"Error in `-.Date`(x, as.Date("2013-01-01")) : 
Can only subtract from Date objects"

All ideas are welcome !

Cheers

Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
Chapo
  • 2,563
  • 3
  • 30
  • 60

1 Answers1

0

It didn't work for me until I loaded the zoo package. Before that it was because of coercion issues between dates and numeric and not supplying an origin. If you try detach(package:zoo) and run:

 a <- as.Date("2012-10-01"):as.Date("2013-10-01")

myFun <- function (x) {
    return(sqrt(abs( x - as.numeric( as.Date( "2013-01-01" ) ) ) ) )
}
sapply(a,myFun)

I get back the same thing that I do when I load package zoo. The reason is that (on my R session) without zoo running, the first command results in:

 as.Date(as.Date("2012-10-01"):as.Date("2013-03-25"))

Results in:

Error in as.Date.numeric(as.Date("2012-10-01"):as.Date("2013-03-25")) : 
  'origin' must be supplied
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • Thank you for your answer. It does work but I'm not sure why... The zoo or base package should be able to handle conversion from a difference of dates to numeric no ? – Chapo Mar 14 '13 at 18:47
  • @Chapo without `zoo` loaded the first line returns a vector of integer number of days since the epoch began. Then in the function we turn the date you want to subtract also into an integer using the default origin. Does that make sense? – Simon O'Hanlon Mar 14 '13 at 18:50
  • It does make sense but I was trying to do everything using dates instead of their integer representation. In fact, The base package doesn't handle direct basic operations on dates, hence my mistake. Thank you for the answer. – Chapo Mar 14 '13 at 18:54