I have a moved a function I created into an R package and it has stopped working. I get an error:
Error in `:=`((value), 1) :
Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").
Weirdly this works if I load the function into the environment but not from the package? it seems very weird behaviour... I even check for whether it is a data.table
in the function to stop this very thing!
data = as.data.table(mtcars)
# I Go into the package, highlight the function and run the code, to load the function into the environment
# This works
create_dummy_var(data, var="cyl")
# This doesn't work (get the error message from above)
myPackage::create_dummy_var(data, var="cyl")
The original whole function
#' Converts a variable into a dummy variable
#'
#' Converts a single variable which contains a limited number of values into numeous dummary variables,
#' of 1 if the value is present 0 otherwise. The number of createds vars is equal to the number of unique observations in the varaiable
#'
#' @param dtable A data.table (must be data.table NOT data.frame or tibble)
#' @param var The variable to operate on
#'
#' @return data.table
#' @export
#'
#' @examples
#'
#' df = data.frame("alp" = c("a", "a", "b", "d", "b"), "adults" = 1:5)
#'
#' dt = data.table::data.table(df)
#'
#' create_dummy_var(dt, "alp")
create_dummy_var <- function(dtable, var) {
if (!var %in% names(dtable)) stop(var, " not found in dt")
if(all(class(dtable) != "data.table")) stop("dt must be a data.table")
dtable[, value := 1L]
dcast(dtable , ... ~ dtable[[var]] , value.var = "value", fill = 0, with = FALSE)
}
To replicate put this into an R package (you can use RStudio's new project, New Package template for the boiler plate).
> packageVersion("data.table")
[1] ‘1.14.2’