加载 R 包时出错:“检查 is.data.table(DT) == TRUE

Error when loading R package: "Check that is.data.table(DT) == TRUE

以下 运行 在控制台中没问题:

library(data.table)
dt = data.table(x = 1:5)
dt[, y := 1]

但是如果我将这些行包含在一个包中,并使用 devtools::load_all(".") 加载它,我会得到这个错误:

Error in `:=`(y, 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 是导入的,因为它不会在第二行失败。那么这里有什么问题,我该怎么做呢运行?

包是通过usethis::create_package()创建的,只有这三行代码。这是我能做的最简单的重复。如果我将代码放在一个函数中并通过 roxygen2 ("' @import data.table) 加载 data.table,我会得到同样的错误。我在 DESCRIPTION Imports 中确实有 data.table (>= 1.14.0)

错误有以下踪迹:

14. stop("Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways.
See help(\":=\").") 
13. `:=`(y, 1) 
12. `[.data.frame`(x, i, j) 
11. `[.data.table`(dt, , `:=`(y, 1)) at tmp.R#3
10. dt[, y := 1] at tmp.R#3
9. eval(exprs[i], envir) 
8. eval(exprs[i], envir) 
7. source_one(file, encoding, envir = envir) 
6. source_many(paths, encoding, env) 
5. force(code) 
4. withr_with_dir(path, source_many(paths, encoding, env)) 
3. load_code(path) 
2. pkgload::load_all(path = path, reset = reset, recompile = recompile, 
    export_all = export_all, helpers = helpers, quiet = quiet, 
    ...) 
1. devtools::load_all(".")  

sessionInfo():

R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.14.0

loaded via a namespace (and not attached):
 [1] rstudioapi_0.13   magrittr_2.0.1    usethis_2.0.1     devtools_2.3.2    pkgload_1.2.0    
 [6] R6_2.5.0          rlang_0.4.10      fastmap_1.1.0     tools_4.0.3       pkgbuild_1.2.0   
[11] xfun_0.21         sessioninfo_1.1.1 tinytex_0.30      cli_2.3.1         withr_2.4.1      
[16] ellipsis_0.3.1    remotes_2.2.0     assertthat_0.2.1  rprojroot_2.0.2   lifecycle_1.0.0  
[21] crayon_1.4.1      processx_3.4.5    purrr_0.3.4       callr_3.5.1       fs_1.5.0         
[26] ps_1.6.0          testthat_3.0.2    memoise_2.0.0     glue_1.4.2        cachem_1.0.4     
[31] compiler_4.0.3    desc_1.3.0        prettyunits_1.1.1

解决方案:使用 roxygen2 将其添加到您的包中的某处:

#' @importFrom data.table ":="
NULL

这会将 importFrom(data.table,":=") 写入您的 NAMESPACE 文件。