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

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

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

问题

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

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

  1. > library(stringr, include.only = 'str_length')
  2. > str_length('a')
  3. [1] 1
  4. > library(stringr, include.only = 'str_sub')
  5. > str_sub('a')
  6. Error in str_sub('a') : 找不到函数“str_sub
  7. > str_length('a')
  8. [1] 1

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

  1. > devtools::unload('stringr')
  2. > 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:

  1. > library(stringr, include.only = 'str_length')
  2. > str_length('a')
  3. [1] 1
  4. > library(stringr, include.only = 'str_sub')
  5. > str_sub('a')
  6. Error in str_sub("a") : could not find function "str_sub"
  7. > str_length('a')
  8. [1] 1

so far the workaround is to unload package then reload

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

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

答案1

得分: 2

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

  1. str_length <- stringr::str_length
  2. str_length('a')
  3. # 1
  4. str_sub <- stringr::str_sub
  5. str_sub('a')
  6. # "a"
  7. str_length('a')
  8. # 1

或者您可以使用 box

  1. box::use(stringr[str_length])
  2. str_length('a')
  3. # 1
  4. box::use(stringr[str_sub])
  5. str_sub('a')
  6. # "a"
  7. str_length('a')
  8. # 1
英文:

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

  1. str_length &lt;- stringr::str_length
  2. str_length(&#39;a&#39;)
  3. # 1
  4. str_sub &lt;- stringr::str_sub
  5. str_sub(&#39;a&#39;)
  6. # &quot;a&quot;
  7. str_length(&#39;a&#39;)
  8. # 1

Or you could use box:

  1. box::use(stringr[str_length])
  2. str_length(&#39;a&#39;)
  3. # 1
  4. box::use(stringr[str_sub])
  5. str_sub(&#39;a&#39;)
  6. # &quot;a&quot;
  7. str_length(&#39;a&#39;)
  8. # 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:

确定