Вопрос

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

Это было полезно?

Решение

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top