15
votes

I have a function to remove empty columns from a data.table, and included that in a package.

Somehow it works when I load the function, but not when I call it from the package. Question: why doesn't this function run when I call it from a package?

There is no require(data.table) or library(data.table) in any of the functions in the package. DESCRIPTION file contains: Imports: data.table. So Using data.table package inside my own package is satisfied.

library(data.table)
df = data.table(a = c(1,2,3), b = c(NA, NA, NA), c = c(4,5,6))
library(cr360)

remove.emptycols(df) # from package
Error in .subset(x, j) : invalid subscript type 'list'

# now open function from mypackage and run again:
# source("./mypackage/R/fun_remove_emptycols.R")
remove.emptycols(df)
   a c
1: 1 4
2: 2 5
3: 3 6

the function:

#' Remove empty columns
#' 
#' Counts the number of NA values in the columns and counts the number of rows.
#' @param df
#' @return df data.table with empty columns removed.
#' @export
#' 
#' 
remove.emptycols = function(df) {

count.colNA = df[,lapply(.SD, function(x) sum(is.na(x)))] 
df = df[,which(count.colNA != nrow(df)),with = FALSE]  

return(df)
}
1
Strange. Have you rebuilt your package with the new DESCRIPTION file and reinstalled your package? - Matt Dowle
I did. Also tried the modules package [more python like module approach alternative for packages], same result. Built and reloaded package. Build and restarted R: same result. Am now just loading the functions in a new namespace: utils = new.env(), source(utils$remove.emptycols = function ....That works fine. - Henk
Oh. Please paste result of sessionInfo(), packageVersion("data.table") and does your package have a NAMESPACE file? - Matt Dowle
Long output, so here are the files: copy.com/4hN8Mm1LyrpH copy.com/q7SQFqLqjfhm - Henk
There appears to be a line break: Imports: \n data.table. Remove that so the field is one line, rebuild, reinstall and retry. - Matt Dowle

1 Answers

14
votes

The text

import(data.table)

needs to be in the NAMESPACE file as well as data.table being in the Imports: field in the DESCRIPTION field. I've edited the linked question and updated FAQ 6.9.
Using data.table package inside my own package

Also, in RStudio be aware of the option "Use Roxygen to build NAMESPACE file" and see:
Does roxygen2 automatically write NAMESPACE directives for "Imports:" packages?


Previous red herring kept for posterity ...

Not sure, but your package's DESCRIPTION contained :

...
Version: 1.0
Date: 2014-06-23
Imports:
    data.table
Author: Henk
Description: utility functions
...

Try removing the line break and this instead :

...
Version: 1.0
Date: 2014-06-23
Imports: data.table
Author: Henk
Description: utility functions
...