[R-pkg-devel] Using data.table in a package
Duncan Murdoch
murdoch@dunc@n @end|ng |rom gm@||@com
Fri Mar 5 14:49:32 CET 2021
On 05/03/2021 8:27 a.m., Martin Møller Skarbiniks Pedersen wrote:
> Hi,
>
> I am converting a couple of functions into a R-package. Many of the
> functions use data.table.
> I have two questions using data.table in my own package.
> Normally I would put each question in separate emails but I think they
> might be connected.
>
> First question is short and I think the answer is yes.
> 1. Do I always need to prefix data.table each time I use something from
> that package?
> Eg. DT <- data.table::data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6),
> v=1:9)
No, you could import that function. This is done in the NAMESPACE file.
If you're using roxygen2, you can put in comments that will write the
appropriate lines to NAMESPACE.
>
> Second question is longer.
> 2. In this small example code:
> hello <- function() {
> DT <- data.table::data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6),
> v=1:9)
> DT[, .(sum(v))]
> }
>
> I get these warnings from R CMD check:
> hello: no visible global function definition for ‘.’
> hello: no visible binding for global variable ‘v’
> Undefined global functions or variables:
> . v
>
> According to: vignette("datatable-importing", package = "data.table")
> The solution is
> hello <- function() {
> v <- NULL
> . <- NULL
>
> And it works but looks a bit weird.
> Is there a better solution?
The problem is that data.table is using non-standard evaluation.
Syntactically it looks like it is referencing global variables, but in
fact it is not, and you need to tell the testing code that what you are
doing is okay.
The suggestion of assigning NULL to the variables is one way. Another
is to declare . and v as global variables using
globalVariables(c(".", "v"))
outside of your function, and that will suppress warnings about them.
You could also put the NULL assignments outside the function and it
would have the same effect. (You don't want to export those variables,
so be careful with your NAMESPACE file.)
Duncan Murdoch
More information about the R-package-devel
mailing list