stacking multiple calls of library(…, include.only=…) doesn’t work

huangapple go评论59阅读模式
英文:

stacking multiple calls of library(…, include.only=…) doesn’t work

问题

自R 3.6版本开始,可以在加载包时使用library(…, include.only=…)选择要加载的函数。

但有时我需要临时加载其他函数,而堆叠多个library(…, include.only=…)不起作用:

> library(stringr, include.only = 'str_length')
> str_length('a')
[1] 1
> library(stringr, include.only = 'str_sub')
> str_sub('a')
Error in str_sub('a') : 找不到函数“str_sub”
> str_length('a')
[1] 1

到目前为止,解决方法是卸载包,然后重新加载:

> devtools::unload('stringr')
> library(stringr, include.only = c('str_length', 'str_sub'))

是否有其他方法可以在不重新加载包的情况下按需加载函数?

英文:

As of R 3.6 it’s possible to choose functions when loading a package with library(…, include.only=…).

But sometimes I’d need other functions on the fly, and stacking multiples library(…, include.only=…) doesn’t work:

> library(stringr, include.only = 'str_length')
> str_length('a')
[1] 1
> library(stringr, include.only = 'str_sub')
> str_sub('a')
Error in str_sub("a") : could not find function "str_sub"
> str_length('a')
[1] 1

so far the workaround is to unload package then reload

> devtools::unload('stringr')
> library(stringr, include.only = c('str_length', 'str_sub'))

is there another way to load functions on demand without reloading package?

答案1

得分: 2

一种选择是将各个函数分配到全局环境中:

str_length <- stringr::str_length
str_length('a')
# 1

str_sub <- stringr::str_sub
str_sub('a')
# "a"

str_length('a')
# 1

或者您可以使用 box

box::use(stringr[str_length])

str_length('a')
# 1

box::use(stringr[str_sub])
str_sub('a')
# "a"

str_length('a')
# 1
英文:

One option would be to assign individual functions into the global environment:

str_length &lt;- stringr::str_length
str_length(&#39;a&#39;)
# 1

str_sub &lt;- stringr::str_sub
str_sub(&#39;a&#39;)
# &quot;a&quot;

str_length(&#39;a&#39;)
# 1

Or you could use box:

box::use(stringr[str_length])

str_length(&#39;a&#39;)
# 1

box::use(stringr[str_sub])
str_sub(&#39;a&#39;)
# &quot;a&quot;

str_length(&#39;a&#39;)
# 1

huangapple
  • 本文由 发表于 2023年2月8日 20:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定