I have a problem with R, a chron object and sapply function. I changed the default origin:
chron_start <- chron("01/01/2010", "00:30:00",origin.=c(month=1, day=1, year=1900))
ch <- chron_start+(0:(365*24-1))/24
Now, if I run:
> sprintf("%s", years(ch[1]))
[1] "2010"
But, If I run it iteratively with sapply I get:
> anios <- sapply(ch, function(x){sprintf("%s", years(x))})
> anios[1]
[1] "2080"
So it gets 70 years ahead, which is the difference between my origin (1900) and the defaults origin (1970).
I'd like to ask if this happens to you to, in order to send a bug report, or if there is an explanation to this behaviour and how to solve it.
Thanks in advance!!
P.S.: my R version is "R version 3.4.2 (2017-09-28)", running on GNU/Linux openSUSE Leap 42.2 64 bits. Chron package version is 2.3-45
I would try not to use non-default origins with chron or at least convert them to default origins as soon as you can.
Here we create ch0
which represents the same date times as ch
but with default origin. The chron package does have the origin
function (as well as the origin<-
function) to help with this but it is not exported so we must preface it with chron:::
.
ch0 <- chron(ch, origin = chron::origin(chron(0)))
# now we get the expected years
anios <- sapply(ch0, function(x){sprintf("%s", years(x))})
head(anios)
## [1] "2010" "2010" "2010" "2010" "2010" "2010"
Note: An alternative to the expression for ch0
above would be:
ch0 <- ch
chron:::origin(ch0) <- chron:::origin(chron(0))
Also the sapply
could be replaced with:
format(years(ch0))
and without the sapply we don't even need ch0
so this works:
format(years(ch))
Update: As of chron ‘2.3.51’ (which was just uploaded to CRAN) origin
is exported so the first line of code above no longer needs chron:::
ch0 <- chron(ch, origin = origin(chron(0)))
Update 2: Have updated Note.