繁体   English   中英

使用 get() 从未加载的 package 中检索函数

[英]Using get() to retrieve functions from a package that is not loaded

我可以使用get访问函数,如下所示:

get("sum")
# function (..., na.rm = FALSE)  .Primitive("sum")

If I want to get a function from a package, I can load the package and then get the function:

library(data.table)
get("uniqueN")

# function (x, by = if (is.list(x)) seq_along(x) else NULL, na.rm = FALSE) 
# {
#   if (is.null(x)) 
#     return(0L)
#   if (!is.atomic(x) && !is.data.frame(x)) 
#     stop("x must be an atomic vector or data.frames/data.tables")
#   if (is.atomic(x)) {
#     if (is.logical(x)) 
#       return(.Call(CuniqueNlogical, x, na.rm = na.rm))
#     x = as_list(x)
#   }
#   o = forderv(x, by = by, retGrp = TRUE, na.last = if (!na.rm) 
#     FALSE
#     else NA)
#   starts = attr(o, "starts", exact = TRUE)
#   if (!na.rm) {
#     length(starts)
#   }
#   else {
#     sum((if (length(o)) o[starts] else starts) != 0L)
#   }
# }
# <bytecode: 0x5559622e2f60>
#   <environment: namespace:data.table>

现在,假设我想在加载 package 的情况下执行此操作。 我最初的想法是,

get("data.table::uniqueN")
# Error in get("data.table::uniqueN") : 
#   object 'data.table::uniqueN' not found

显然,这是行不通的。 get中,我可以指定查找 object 的环境(即,使用envir参数),但由于 package 未加载,大概还没有ZEFE90A8E604A7C840E88D03AD8Z 环境。


问题:如何从未加载的 package 中get function?

get有一个envir参数,您可以通过getNamespace获取 package 的命名空间,而无需将其附加到搜索路径,因此一种选择是:

get("uniqueN", envir = getNamespace('data.table'))
#> function (x, by = if (is.list(x)) seq_along(x) else NULL, na.rm = FALSE) 
#> {
#>     if (is.null(x)) 
#>         return(0L)
#>     if (!is.atomic(x) && !is.data.frame(x)) 
#>         stop("x must be an atomic vector or data.frames/data.tables")
#>     if (is.atomic(x)) {
#>         if (is.logical(x)) 
#>             return(.Call(CuniqueNlogical, x, na.rm = na.rm))
#>         x = as_list(x)
#>     }
#>     o = forderv(x, by = by, retGrp = TRUE, na.last = if (!na.rm) 
#>         FALSE
#>     else NA)
#>     starts = attr(o, "starts", exact = TRUE)
#>     if (!na.rm) {
#>         length(starts)
#>     }
#>     else {
#>         sum((if (length(o)) o[starts] else starts) != 0L)
#>     }
#> }
#> <bytecode: 0x000001c545c5e208>
#> <environment: namespace:data.table>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM