data.table := 不在包函数中工作

2024-04-25

我已将创建的函数移至 R 包中,但它已停止工作。我收到错误:

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(":=").

奇怪的是,如果我将函数加载到环境中而不是从包中加载,这会起作用吗?这看起来很奇怪的行为......我什至检查它是否是data.table在函数中阻止这件事!


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")

原来的全功能

#' 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)
}

要复制,请将其放入 R 包中(您可以使用 RStudio 的新项目,即样板的新包模板)。

> packageVersion("data.table")
[1] ‘1.14.2’

感谢 jangorecki 指出导入 data.table 小插图 https://cran.r-project.org/web/packages/data.table/vignettes/datatable-importing.html

该问题正在声明data.table命名空间中的特殊符号。

导入 data.table 小插图没有提到如果您使用 roxygen2 生成 NAMESPACE 那么您不能使用import(data.table)在命名空间中。但一如既往的优秀usethis包装已覆盖,并带有usethis::use_data_table()。这将创建所有样板并且现在可以工作了:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

data.table := 不在包函数中工作 的相关文章

随机推荐