bers
bers

Reputation: 5771

Why is this code working in the R console, but not as part of an R package?

This code is working fine:

data.table::data.table(A = c(2, 1))[order(A), ]

It prints:

   A
1: 1
2: 2

I can wrap this code inside a function just fine, too (same output):

bug <- function() {
    data.table::data.table(A = c(2, 1))[order(A), ]
}
bug()

However, putting this function into a package and calling Bug::bug()does not work for some reason, giving me

Error in order(A) : object 'A' not found
Calls: <Anonymous> -> [ -> [.data.table -> [.data.frame -> order
Execution halted

Here is how to reproduce this problem:

File DESCRIPTION:

Package: Bug
Title: Bug
Version: 0.0.0.0001
Description: Bug
License: GPLv3
Imports: data.table
Encoding: UTF-8
RoxygenNote: 7.1.1

File R/Bug.R:

#' @export
bug <- function() {
    data.table::data.table(A = c(2, 1))[order(A), ]
}

Then cd into the directory where DESCRIPTION is and issue

R -e "devtools::document(); devtools::install(); Bug::bug()"

Upvotes: 4

Views: 122

Answers (1)

user2554330
user2554330

Reputation: 44788

The data.table package does some strange non-standard evaluation. It tries to figure out whether your package wants to support that or not, and in your case, decided "not".

I think this is documented behaviour, but I'd call it a design flaw, if not a bug.

You can force it to support the NSE by putting

.datatable.aware <- TRUE

somewhere in your package source code.

Upvotes: 3

Related Questions