Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot xts function find as.yearmon function without attaching zoo?

Tags:

r

zoo

xts

If you have a fresh R session (no packages attached except those from base) and try to create the following xts object ordered by a yearmon class...

df <- data.frame(date = zoo::as.yearmon(seq.Date(as.Date("2015-01-01"),
                                                 as.Date("2015-12-31"),
                                                 by = "month")),
                 num = rnorm(12, 0, 1))

dates <- df[,1]

xts::xts(as.matrix(df[, -1]), order.by = dates)

you get the following error.

enter image description here

I thought I understood the R namespace framework, but in this case I'm completely lost. Why is that xts tries to call the as.yearmon function when the dates object is already a yearmon object? I am aware that xts depends on zoo but is that the reason?

If zoo is attached then of course the error goes away.

The reason why I am interested in this issue is that I am creating a package that uses the xts package. One of my functions return a xts object, but I would like my package to only depend on R and import all the other packages - which is described as best practice by Hadley Wickham (as I understand it). However, because of this issue I need to depend the zoo package to make this work.

I'm sure that I'm overlooking something, so I hope a friendly soul here at SO can help explain this issue and present a solution. Thanks!

like image 877
P. Garnry Avatar asked Sep 25 '22 19:09

P. Garnry


2 Answers

This is an issue with the current version of xts on CRAN. It has been fixed in the development version of xts on GitHub. The problem was that all the zoo functions xts used internally were not imported in the NAMESPACE.

R> df <- data.frame(date = zoo::as.yearmon(seq.Date(as.Date("2015-01-01"),
+                                                  as.Date("2015-12-31"),
+                                                  by = "month")),
+                  num = rnorm(12, 0, 1))
R> 
R> dates <- df[,1]
R> 
R> xts::xts(as.matrix(df[, -1]), order.by = dates)
               [,1]
Jan 2015 -1.2141571
Feb 2015 -0.7645339
Mar 2015 -0.7555164
Apr 2015 -0.6596672
May 2015  0.2099139
Jun 2015 -0.3374191
Jul 2015  1.1704935
Aug 2015 -2.2101577
Sep 2015  0.7623118
Oct 2015  0.3643535
Nov 2015 -1.2789485
Dec 2015  1.0316663
R> search()
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base"     
R> packageVersion('xts')
[1] ‘0.9.8’
like image 167
Joshua Ulrich Avatar answered Nov 10 '22 17:11

Joshua Ulrich


With the update to xts version 0.10 on CRAN this is no longer an issue

like image 37
Chitown Avatar answered Nov 10 '22 18:11

Chitown