Data.table [, - c (...)] behaves differently if defined in a package
UPD. Thanks to @RYoda, I discovered that I forgot to include import(data.table)
in my NAMESPACE
file. However, I still don't understand why all other functions data.table
work fine even without it import()
, would be grateful if someone can explain it.
In my package, I define a function that, among other things, excludes certain columns from the data table. I can define it in different ways:
# code in the package: \testexcl\R\test_exclude.R
test_exclude_col1 <- function(inpDT,col2excl){
output <- inpDT[, -c(col2excl), with=F]
invisible(output)
}
test_exclude_col2 <- function(inpDT,col2excl){
output <- inpDT[, setdiff(names(inpDT), col2excl), with=F]
invisible(output;
}
Then I can use a function like this:
require(data.table)
require(testexcl) # my package
dt.iris <- data.table(iris)
dt.1 <- test_exclude_col1(dt.iris, 'Species') # Error
dt.2 <- test_exclude_col2(dt.iris, 'Species') # OK
test_exclude_col2()
works as expected but test_exclude_col1()
throws an error Error in -c(col2excl) : invalid argument to unary operator
. My biggest concern is that if I define exactly the same code test_exclude_col1()
not in the package, but in my session, it works correctly. Why is this happening?
I'm on R version 3.3.3 (2017-03-06), Win10 x86_64-w64-mingw32 / x64, data.table_1.10.4, tools_3.3.3
PS To make sure I am working with data.table, I added this part to the package:
test_exclude_col1a <- function(inpDT,col2excl){
print(class(inpDT));
inpDT <- data.table(inpDT);
output <- inpDT[, -c(col2excl), with=F]
invisible(output);
}
When I call test_exclude_col1a(dt.iris, 'Species')
it prints [1] "data.table" "data.frame"
, then gives the same error.
source to share
To use a function data.table
in your package, you must
- declare a package dependency so that the package is
data.table
installed if it doesn't already exist (for example, viaImports:
in a fileDESCRIPTION
) and - import the required functions into your package (using the function
import()
in the fileNAMESPACE
=>import(data.table)
For more information see
source to share