如何在不重新启动 R 的情况下卸载包

发布于 2024-11-28 04:32:56 字数 628 浏览 3 评论 0原文

我想卸载一个包而不必重新启动 R (主要是因为当我尝试不同的、冲突的包时重新启动 R 会变得令人沮丧,但可以想象,这可以在程序中使用一个函数,然后使用另一个函数 - 尽管名称空间对于这种用途,引用可能是一个更好的主意)。

?library 不显示任何会卸载包的选项。

有一个建议分离< /code> 可以卸载包,但以下都失败:

detach(vegan)

detach(vegan) 中的错误:name 参数无效

detach("vegan")

detach("vegan") 中的错误:name 参数无效

那么如何卸载包呢?

I'd like to unload a package without having to restart R (mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use).

?library doesn't show any options that would unload a package.

There is a suggestion that detach can unload package, but the following both fail:

detach(vegan)

Error in detach(vegan) : invalid name argument

detach("vegan")

Error in detach("vegan") : invalid name argument

So how do I unload a package?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

[浮城] 2024-12-05 04:32:56

尝试一下(请参阅 ?detach 了解更多详细信息):

detach("package:vegan", unload=TRUE)

可以一次加载包的多个版本(例如,如果您在不同的库中有一个开发版本和一个稳定版本)。为了保证所有副本都被分离,请使用此功能。

detach_package <- function(pkg, character.only = FALSE)
{
  if(!character.only)
  {
    pkg <- deparse(substitute(pkg))
  }
  search_item <- paste("package", pkg, sep = ":")
  while(search_item %in% search())
  {
    detach(search_item, unload = TRUE, character.only = TRUE)
  }
}

用法是,例如

detach_package(vegan)

detach_package("vegan", TRUE)

Try this (see ?detach for more details):

detach("package:vegan", unload=TRUE)

It is possible to have multiple versions of a package loaded at once (for example, if you have a development version and a stable version in different libraries). To guarantee that all copies are detached, use this function.

detach_package <- function(pkg, character.only = FALSE)
{
  if(!character.only)
  {
    pkg <- deparse(substitute(pkg))
  }
  search_item <- paste("package", pkg, sep = ":")
  while(search_item %in% search())
  {
    detach(search_item, unload = TRUE, character.only = TRUE)
  }
}

Usage is, for example

detach_package(vegan)

or

detach_package("vegan", TRUE)
柠栀 2024-12-05 04:32:56

您还可以使用 unloadNamespace 命令,如下所示:

unloadNamespace("sqldf")

该函数在卸载命名空间之前将其分离。

You can also use the unloadNamespace command, as in:

unloadNamespace("sqldf")

The function detaches the namespace prior to unloading it.

杯别 2024-12-05 04:32:56

您可以取消选中 RStudio(包)中的复选框按钮。

RStudio 软件包窗格

You can uncheck the checkbox button in RStudio (packages).

RStudio packages pane

無心 2024-12-05 04:32:56

我尝试了 kohske 写的答案,但再次出错,所以我做了一些搜索,发现这对我有用(R 3.0.2):

require(splines) # package
detach(package:splines)

或者也

library(splines)
pkg <- "package:splines"
detach(pkg, character.only = TRUE)

I tried what kohske wrote as an answer and I got error again, so I did some search and found this which worked for me (R 3.0.2):

require(splines) # package
detach(package:splines)

or also

library(splines)
pkg <- "package:splines"
detach(pkg, character.only = TRUE)
冬天的雪花 2024-12-05 04:32:56

当您在脚本之间来回切换时,有时可能只需要卸载包。这是一个简单的 IF 语句,可以防止在您尝试卸载当前未加载的包时出现的警告。

if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE) 

将其包含在脚本顶部可能会有所帮助。

我希望这会让你开心!

When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.

if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE) 

Including this at the top of a script might be helpful.

I hope that makes your day!

柠檬色的秋千 2024-12-05 04:32:56

detach(package:PackageName) 可以工作,不需要使用引号。

detach(package:PackageName) works and there is no need to use quotes.

渡你暖光 2024-12-05 04:32:56

另一种选择是

devtools::unload("your-package")

这显然也解决了注册的S3方法未删除的问题unloadNamespace()

Another option is

devtools::unload("your-package")

This apparently also deals with the issue of registered S3 methods that are not removed with unloadNamespace()

梦里梦着梦中梦 2024-12-05 04:32:56

另请注意,您只能使用 unload() 一次。如果您第二次使用它而不重新运行 library(),您将收到信息不多的错误消息 invalid 'name' argument

library(vegan)
#> Loading required package: permute
#> Loading required package: lattice
#> This is vegan 2.5-6
detach("package:vegan",  unload=TRUE)
detach("package:vegan",  unload=TRUE)
#> Error in detach("package:vegan", unload = TRUE): invalid 'name' argument

Created on 2020- 05-09 由 reprex 包 (v0.3.0)

Note also that you can only use unload() once. If you use it a second time without rerunning library(), y'll get the not very informative error message invalid 'name' argument:

library(vegan)
#> Loading required package: permute
#> Loading required package: lattice
#> This is vegan 2.5-6
detach("package:vegan",  unload=TRUE)
detach("package:vegan",  unload=TRUE)
#> Error in detach("package:vegan", unload = TRUE): invalid 'name' argument

Created on 2020-05-09 by the reprex package (v0.3.0)

冷夜 2024-12-05 04:32:56

您可以使用 unloadNamespace()尝试删除某个包(及其带来的所有依赖项),但内存占用将依然坚持。不,detach("package:,packageName", unload=TRUE, force = TRUE) 也不起作用。

从全新的控制台或 Session >重新启动 R 使用 pryr 包检查内存:

pryr::mem_used()

# 40.6 MB   ## This will depend on which packages are loaded obviously (can also fluctuate a bit after the decimal)

检查我的 sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

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

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1      Rcpp_1.0.3       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0   
[9] packrat_0.5.0   

让我们加载 Seurat 包并检查新的 内存占用

library(Seurat)
pryr::mem_used()

# 172 MB    ## Likely to change in the future but just to give you an idea

让我们使用unloadNamespace()删除所有内容:

unloadNamespace("Seurat")
unloadNamespace("ape")
unloadNamespace("cluster")
unloadNamespace("cowplot")
unloadNamespace("ROCR")
unloadNamespace("gplots")
unloadNamespace("caTools")
unloadNamespace("bitops")
unloadNamespace("fitdistrplus")
unloadNamespace("RColorBrewer")
unloadNamespace("sctransform")
unloadNamespace("future.apply")
unloadNamespace("future")
unloadNamespace("plotly")
unloadNamespace("ggrepel")
unloadNamespace("ggridges")
unloadNamespace("ggplot2")
unloadNamespace("gridExtra")
unloadNamespace("gtable")
unloadNamespace("uwot")
unloadNamespace("irlba")
unloadNamespace("leiden")
unloadNamespace("reticulate")
unloadNamespace("rsvd")
unloadNamespace("survival")
unloadNamespace("Matrix")
unloadNamespace("nlme")
unloadNamespace("lmtest")
unloadNamespace("zoo")
unloadNamespace("metap")
unloadNamespace("lattice")
unloadNamespace("grid")
unloadNamespace("httr")
unloadNamespace("ica")
unloadNamespace("igraph")
unloadNamespace("irlba")
unloadNamespace("KernSmooth")
unloadNamespace("leiden")
unloadNamespace("MASS")
unloadNamespace("pbapply")
unloadNamespace("plotly")
unloadNamespace("png")
unloadNamespace("RANN")
unloadNamespace("RcppAnnoy")
unloadNamespace("tidyr")
unloadNamespace("dplyr")
unloadNamespace("tibble")
unloadNamespace("RANN")
unloadNamespace("tidyselect")
unloadNamespace("purrr")
unloadNamespace("htmlwidgets")
unloadNamespace("htmltools")
unloadNamespace("lifecycle")
unloadNamespace("pillar")
unloadNamespace("vctrs")
unloadNamespace("rlang")
unloadNamespace("Rtsne")
unloadNamespace("SDMTools")
unloadNamespace("Rdpack")
unloadNamespace("bibtex")
unloadNamespace("tsne")
unloadNamespace("backports")
unloadNamespace("R6")
unloadNamespace("lazyeval")
unloadNamespace("scales")
unloadNamespace("munsell")
unloadNamespace("colorspace")
unloadNamespace("npsurv")
unloadNamespace("compiler")
unloadNamespace("digest")
unloadNamespace("R.utils")
unloadNamespace("pkgconfig")
unloadNamespace("gbRd")
unloadNamespace("parallel")
unloadNamespace("gdata")
unloadNamespace("listenv")
unloadNamespace("crayon")
unloadNamespace("splines")
unloadNamespace("zeallot")
unloadNamespace("reshape")
unloadNamespace("glue")
unloadNamespace("lsei")
unloadNamespace("RcppParallel")
unloadNamespace("data.table")
unloadNamespace("viridisLite")
unloadNamespace("globals")

现在检查sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

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

loaded via a namespace (and not attached):
 [1] tools_3.6.1       stringr_1.4.0     rstudioapi_0.10   pryr_0.1.4        jsonlite_1.6      gtools_3.8.1      R.oo_1.22.0      
 [8] magrittr_1.5      Rcpp_1.0.3        R.methodsS3_1.7.1 stringi_1.4.3     plyr_1.8.4        reshape2_1.4.3    codetools_0.2-16 
[15] packrat_0.5.0     assertthat_0.2.1 

检查内存占用

pryr::mem_used()

# 173 MB

<一个href="https://twitter.com/MattOldach/status/1217595535844106240" rel="noreferrer">截屏演示链接

You can try all you want to remove a package (and all the dependencies it brought in alongside) using unloadNamespace() but the memory footprint will still persist. And no, detach("package:,packageName", unload=TRUE, force = TRUE) will not work either.

From a fresh new console or Session > Restart R check memory with the pryr package:

pryr::mem_used()

# 40.6 MB   ## This will depend on which packages are loaded obviously (can also fluctuate a bit after the decimal)

Check my sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

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

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1      Rcpp_1.0.3       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0   
[9] packrat_0.5.0   

Let's load the Seurat package and check the new memory footprint:

library(Seurat)
pryr::mem_used()

# 172 MB    ## Likely to change in the future but just to give you an idea

Let's use unloadNamespace() to remove everything:

unloadNamespace("Seurat")
unloadNamespace("ape")
unloadNamespace("cluster")
unloadNamespace("cowplot")
unloadNamespace("ROCR")
unloadNamespace("gplots")
unloadNamespace("caTools")
unloadNamespace("bitops")
unloadNamespace("fitdistrplus")
unloadNamespace("RColorBrewer")
unloadNamespace("sctransform")
unloadNamespace("future.apply")
unloadNamespace("future")
unloadNamespace("plotly")
unloadNamespace("ggrepel")
unloadNamespace("ggridges")
unloadNamespace("ggplot2")
unloadNamespace("gridExtra")
unloadNamespace("gtable")
unloadNamespace("uwot")
unloadNamespace("irlba")
unloadNamespace("leiden")
unloadNamespace("reticulate")
unloadNamespace("rsvd")
unloadNamespace("survival")
unloadNamespace("Matrix")
unloadNamespace("nlme")
unloadNamespace("lmtest")
unloadNamespace("zoo")
unloadNamespace("metap")
unloadNamespace("lattice")
unloadNamespace("grid")
unloadNamespace("httr")
unloadNamespace("ica")
unloadNamespace("igraph")
unloadNamespace("irlba")
unloadNamespace("KernSmooth")
unloadNamespace("leiden")
unloadNamespace("MASS")
unloadNamespace("pbapply")
unloadNamespace("plotly")
unloadNamespace("png")
unloadNamespace("RANN")
unloadNamespace("RcppAnnoy")
unloadNamespace("tidyr")
unloadNamespace("dplyr")
unloadNamespace("tibble")
unloadNamespace("RANN")
unloadNamespace("tidyselect")
unloadNamespace("purrr")
unloadNamespace("htmlwidgets")
unloadNamespace("htmltools")
unloadNamespace("lifecycle")
unloadNamespace("pillar")
unloadNamespace("vctrs")
unloadNamespace("rlang")
unloadNamespace("Rtsne")
unloadNamespace("SDMTools")
unloadNamespace("Rdpack")
unloadNamespace("bibtex")
unloadNamespace("tsne")
unloadNamespace("backports")
unloadNamespace("R6")
unloadNamespace("lazyeval")
unloadNamespace("scales")
unloadNamespace("munsell")
unloadNamespace("colorspace")
unloadNamespace("npsurv")
unloadNamespace("compiler")
unloadNamespace("digest")
unloadNamespace("R.utils")
unloadNamespace("pkgconfig")
unloadNamespace("gbRd")
unloadNamespace("parallel")
unloadNamespace("gdata")
unloadNamespace("listenv")
unloadNamespace("crayon")
unloadNamespace("splines")
unloadNamespace("zeallot")
unloadNamespace("reshape")
unloadNamespace("glue")
unloadNamespace("lsei")
unloadNamespace("RcppParallel")
unloadNamespace("data.table")
unloadNamespace("viridisLite")
unloadNamespace("globals")

Now check sessionInfo():

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

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

loaded via a namespace (and not attached):
 [1] tools_3.6.1       stringr_1.4.0     rstudioapi_0.10   pryr_0.1.4        jsonlite_1.6      gtools_3.8.1      R.oo_1.22.0      
 [8] magrittr_1.5      Rcpp_1.0.3        R.methodsS3_1.7.1 stringi_1.4.3     plyr_1.8.4        reshape2_1.4.3    codetools_0.2-16 
[15] packrat_0.5.0     assertthat_0.2.1 

Check the memory footprint:

pryr::mem_used()

# 173 MB

Link to screen-cast demonstration

oО清风挽发oО 2024-12-05 04:32:56

我想添加一个替代解决方案。该解决方案不会直接回答您关于卸载软件包的问题,​​但恕我直言,它提供了一种更清晰的替代方案来实现您期望的目标,据我所知,它广泛关注避免名称冲突并尝试不同的功能,例如指出:

主要是因为当我尝试不同的、冲突的包时重新启动 R 会变得令人沮丧,但可以想象,这可以在程序中使用一个函数,然后使用另一个函数——尽管命名空间引用可能是一个更好的主意

解决方案

函数 with_package 通过 withr 包提供了以下可能性:

将包附加到搜索路径,执行代码,然后从搜索路径中删除该包。但是,包命名空间被卸载。

示例中使用的示例

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point 无法从全局命名空间访问。我认为这可能是比加载和卸载包更干净的处理冲突的方法。

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

燃情 2024-12-05 04:32:56

与@tjebo 答案相连。

TL;博士
请使用 pkgload:::unload 而不是 devtools::unload,因为它们是相同的函数(1 比 1),并且 pkgload 是一个非常多的函数。更轻的包(依赖项的数量)。 devtools 只是重新导出 pkgload:::unload 函数。

不幸的是,devtools 是一个巨大的依赖项(因为 devtools 有很多自己的依赖项),它更有针对性的开发阶段。因此,如果您想在自己的包中使用 unload 函数或者您关心库大小,请记住使用 pkgload:::unload 而不是 devtools::卸载。 devtools 只是重新导出 pkgload:::unload 函数。

请检查 devtools::unload 函数的页脚以快速确认重新导出或转到 github回购协议

> devtools::unload
function (package = pkg_name(), quiet = FALSE) 
{
    if (package == "compiler") {
        oldEnable <- compiler::enableJIT(0)
        if (oldEnable != 0) {
            warning("JIT automatically disabled when unloading the compiler.")
        }
    }
    if (!package %in% loadedNamespaces()) {
        stop("Package ", package, " not found in loaded packages or namespaces")
    }
    unregister_methods(package)
    unloaded <- tryCatch({
        unloadNamespace(package)
        TRUE
    }, error = function(e) FALSE)
    if (!unloaded) {
        unload_pkg_env(package)
        unregister_namespace(package)
    }
    clear_cache()
    unload_dll(package)
}
<bytecode: 0x11a763280>
<environment: namespace:pkgload>

Connected with @tjebo answer.

TL;DR
Please use pkgload:::unload instead of devtools::unload as they are the same function (1 to 1) and pkgload is a much lighter package (nr of dependencies). devtools simply reexporting the pkgload:::unload function.

Unfortunately devtools is a huge dependency (as devtools has a lot of own dependencies), which is more development stage targeted. So if you want to use the unload function in your own package or you care about library size please remember to use pkgload:::unload instead of devtools::unload. devtools simply reexporting the pkgload:::unload function.

Please check the footer of the devtools::unload function to quickly confirm the reexport or go to the github repo

> devtools::unload
function (package = pkg_name(), quiet = FALSE) 
{
    if (package == "compiler") {
        oldEnable <- compiler::enableJIT(0)
        if (oldEnable != 0) {
            warning("JIT automatically disabled when unloading the compiler.")
        }
    }
    if (!package %in% loadedNamespaces()) {
        stop("Package ", package, " not found in loaded packages or namespaces")
    }
    unregister_methods(package)
    unloaded <- tryCatch({
        unloadNamespace(package)
        TRUE
    }, error = function(e) FALSE)
    if (!unloaded) {
        unload_pkg_env(package)
        unregister_namespace(package)
    }
    clear_cache()
    unload_dll(package)
}
<bytecode: 0x11a763280>
<environment: namespace:pkgload>
没有心的人 2024-12-05 04:32:56

只需转到“输出”窗口,然后单击“包”图标(它位于绘图和帮助图标之间)。从您想要卸载的包裹中删除“勾号/复选标记”。

要再次使用该包,只需在包前面添加“勾号或复选标记”或使用:

library (lme4)

Just go to OUTPUT window, then click on Packages icon (it is located between Plot and Help icons). Remove "tick / check mark" from the package you wanted be unload.

For again using the package just put a "tick or Check mark" in front of package or use :

library (lme4)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文