Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data.table function works in script but not in package

Tags:

r

data.table

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)
}
like image 860
Henk Avatar asked Jun 24 '14 07:06

Henk


1 Answers

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
...
like image 76
Matt Dowle Avatar answered Oct 26 '22 22:10

Matt Dowle