Knitr: R package check error, object 'opts_chunk' not found - r

I am getting the following error when checking my R package
> Error: could not find function "locdata"
> Execution halted
> when running code in ‘DFSurvey.Rnw’
> ...
>
> > opts_chunk$set(cache = TRUE, fig.path = "DFSurveyImages/", dev = "pdf")
>
> When sourcing ‘DFSurvey.R’:
> Error: object 'opts_chunk' not found
> Execution halted
Yihui Xie (knitr developer) said that was because in RStudio, knitr was not set as the method for weaving .Rnw files, https://groups.google.com/forum/?fromgroups#!topic/knitr/9672CBbc8CM. I have knitr set in both the tools and build options, in the R package DESCRIPTION file I have:
VignetteBuilder: knitr
Suggests: knitr
and in the vignette I have:
%\VignetteEngine{knitr}
%\VignetteDepends{knitr,xtable,TSP}
When I use compile the pdf in RStudio or use knit("KNITR.Rnw"), it compiles correctly. When I check the package, I get the above errors for each vignette. I even put
require(knitr)
before my opts_chunk$set statement. That did not help. I have also run the check from the command line and gotten the same error. Thank you for any help.
Knitr is a useful package. I run long simulations in vignettes, and the cache makes it possible to correct errors without running the simulations over each time. It does not have the problem of trying to find the Sweave.sty file either.
Here is my sessionInfo()
> R version 3.0.0 (2013-04-03)
> Platform: x86_64-apple-darwin10.8.0 (64-bit)
>
> locale:
> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
>
> attached base packages:
> [1] tcltk grid stats graphics grDevices utils datasets methods
> [9] base
>
> other attached packages:
> [1] DualFrame_0.5 xtable_1.7-1 TSP_1.0-7
> [4] maptools_0.8-23 lattice_0.20-15 foreign_0.8-53
> [7] spsurvey_2.5 sp_1.0-9 stringr_0.6.2
> [10] sqldf_0.4-6.4 RSQLite.extfuns_0.0.1 chron_2.3-43
> [13] gsubfn_0.6-5 proto_0.3-10 RSQLite_0.11.3
> [16] DBI_0.2-7 knitr_1.2 gpclib_1.5-5
>
> loaded via a namespace (and not attached):
> [1] deldir_0.0-22 digest_0.6.3 evaluate_0.4.3 formatR_0.7 MASS_7.3-26
> [6] rgeos_0.2-17 tools_3.0.0

put library(knitr) before this opts_chunk$set(cache = TRUE, fig.path = "DFSurveyImages/", dev = "pdf")

You have to load the knitr library first, try this:
```{r setoptions, echo=FALSE}
library(knitr)
opts_chunk$set(cache = TRUE, fig.path = "DFSurveyImages/", dev = "pdf")```

For a knitr vignette that you can compile using knit() or with the "Compile PDF" button in RStudio, but that gets an
Error: object 'opts_chunk' not found
Execution halted
error when checking or building the package, the package check code is not recognizing that your .Rnw file should be knited and not Sweaveed. Check that you have the following:
The vignettes are in the vignette directory, if you have R 3.0.0 or
higher (this was the solution to this post),
cran.r-project.org/doc/manuals/r-devel/R-exts.html#Non_002dSweave-vignettes
Include %\VignetteEngine{knitr::knitr} in the vignette metadata,
yihui.name/knitr/demo/vignette/
Specify VignetteBuilder: knitr in the package DESCRIPTION file, and
Add Suggests: knitr in DESCRIPTION if knitr is needed only for
vignettes
If that does not work add a require(knitr) statement before you set your global options in opts_chunk(), as Ben Bolker, Yuhui and Tyler Rinker suggested.
If in RStudio:
In BOTH the Build configuration and Tool options, set the Sweave option to knitr, www.rstudio.com/ide/docs/authoring/rnw_weave

Changing the Sweave option to knitr in the Tools options worked for me.

I run into this same problem today. Before it was always good. The error message was:
Quitting from lines 14-49 (report.Rmd)
Error in eval(expr, envir, enclos) : object 'opts_chunk' not found
I first specified library(knitr) right before the global options. Did not help.
I specified the name space before the opts_chunk and it worked, like knitr::opts_chunk.

Related

How to detach formula.tools in R without restarting the session [duplicate]

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?
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)
You can also use the unloadNamespace command, as in:
unloadNamespace("sqldf")
The function detaches the namespace prior to unloading it.
You can uncheck the checkbox button in RStudio (packages).
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)
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!
detach(package:PackageName) works and there is no need to use quotes.
Another option is
devtools::unload("your-package")
This apparently also deals with the issue of registered S3 methods that are not removed with unloadNamespace()
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
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)
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.
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)
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>

How to silent R when loading libraries in command line? [duplicate]

I have a package in R (ROCR) that I need to load in my R environment. Upon loading the package, a set of messages are printed. This is ordinarily fine, but since the output of my R script is being used for further analysis I want to completely disable all of this output. How do I do that? Furthermore, I'd prefer to do it without having to modify ROCR at all, so that future users of this script don't have to do that either.
So far:
sink() doesn't work here - redirecting both stdout and std err to /dev/null does nothing for me.
Unsurprisingly, options(warnings=-1) does nothing either, since these are not warnings, per se, being printed.
Any thoughts?
Just use suppressMessages() around your library() call:
edd#max:~$ R
R version 2.14.1 (2011-12-22)
Copyright (C) 2011 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-pc-linux-gnu (64-bit)
[...]
R> suppressMessages(library(ROCR))
R> # silently loaded
R> search()
[1] ".GlobalEnv" "package:ROCR" # it's really there
[3] "package:gplots" "package:KernSmooth"
[5] "package:grid" "package:caTools"
[7] "package:bitops" "package:gdata"
[9] "package:gtools" "package:stats"
[11] "package:graphics" "package:grDevices"
[13] "package:utils" "package:datasets"
[15] "package:methods" "Autoloads"
[17] "package:base"
R>
Use suppressPackageStartupMessages, see the answer by MehradMahmoudian. For completeness, adding here examples of usage:
For one library, use suppressPackageStartupMessages(...), for example:
suppressPackageStartupMessages(library(ggplot2))
For multiple libraries, use suppressPackageStartupMessages({...}), for example:
suppressPackageStartupMessages({
library(ggplot2)
library(ggdendro)
})
SEE ALSO:
Suppress package startup messages
Dirk's answer suppresses all messages and is not specific to messages that is generated while loading packages.
The more accurate solution to the asked question is:
suppressPackageStartupMessages(library("THE_PACKAGE_NAME"))
A bit more detailed explanation can be found here
library(ROCR, quietly = TRUE) might be a more elegant option.
If you load packages with a for loop, then you have to silent the complete loop like I show below instead of suppressing the message when loading the library individually.
requiredPackages = c('plyr','dplyr','data.table')
suppressMessages(
for (p in requiredPackages) {
if (!require(p, character.only = TRUE)){
install.packages(p)
}
library(p, character.only = TRUE)
}
)
By adding quietly = T as shown below will solve the issue:
suppressWarnings(suppressMessages(library("dplyr", quietly = T)))
In case of multiple package you can use :
## specify the package names
PKGs <- c("affy","gcrma","readxl","ggplot2","lattice" )
and them use lapply as below:
lapply(PKGs, library, character.only = TRUE ,quietly = T)

using -knitr- to weave Rnw files in RStudio

This seems to be a recurrent problem for who is willing to write dynamic documents with knitr in RStudio (see also here for instance).
Unfortunately I haven't find a solution on Stack Overflow or by googling more in general.
Here is a toy example I am trying to compile in RStudio. It is the minimal-example-002.Rnw (link):
\documentclass{article}
\usepackage[T1]{fontenc}
\begin{document}
Here is a code chunk.
<<foo, fig.height=4>>=
1+1
letters
chartr('xie', 'XIE', c('xie yihui', 'Yihui Xie'))
par(mar=c(4, 4, .2, .2)); plot(rnorm(100))
#
You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$, and \Sexpr{1.598673e8} is a big number.
\end{document}
My problem is that I am not able to compile the pdf in RStudio by using knitr, while by changing the default weaving option to sweave I get the final pdf.
More specifically, I work in Windows 7, latest RStudio version (0.98.1103), I weave the file using the knitr option and I disabled the "always enable Rnw concordance" box.
Did this happen to you?
Any help would be highly appreciated, thank you very much.
EDIT
Apparently it is not an RStudio problem, as I tried to compile the document from R with:
library('knitr')
knit('minimal_ex.Rnw')
and I get the same error:
processing file: minimal_ex.Rnw
|
| | 0%
|
|...................... | 33%
ordinary text without R code
|
|........................................... | 67%
label: foo (with options)
List of 1
$ fig.height: num 4
Quitting from lines 8-10 (minimal_ex.Rnw)
Errore in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 3, 0
Inoltre: Warning messages:
1: In is.na(res[, 1]) :
is.na() applied to non-(list or vector) of type 'NULL'
2: In is.na(res) : is.na() applied to non-(list or vector) of type 'NULL'
EDIT 2:
This is my session info:
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=Italian_Italy.1252 LC_CTYPE=Italian_Italy.1252 LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C
[5] LC_TIME=Italian_Italy.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] knitr_1.10.5
loaded via a namespace (and not attached):
[1] tools_3.1.1
After spending hours to try to figure out the problem, I updated R (v 3.2.0) and everything works fine now.
It is not clear if the problem was due to some packages conflict, for sure it wasn't an RStudio problem (as I had initially thought).
To add a little to this: It seems to be a bug with the echo parameter which defaults to TRUE. Setting it to false with knitr and pdfLaTeX as a renderer worked for me. In case you're in a situation where you can't update because of dependencies and/or rights issues, this input might be a helpful adhoc fix, since the error message is pretty useless.

Vignette can't find data files during devtools::check

When I run devtools::check() to build my package and the generate the html file of the rmarkdown vignette, I get an error that the data files can't be found. The html file can be built using any of these:
knitr::knit2html('vignettes/myvignette.Rmd') # works fine
devtools::build_vignettes() # works fine
devtools::build() # works fine
But when I run devtools:check() I get:
mydata <- read.csv("data/mycsv.csv")
Warning in file(file, "rt") :
cannot open file 'data/mycsv.csv': No such file or directory
When sourcing 'myvignette.R':
Error: cannot open the connection
Execution halted
How can I get devtools::check() to work? system.file may be relevant but I haven't been able to adapt it to solve my problem. I realise that using rda data files might be a workaround, but I want to use plain text files to store the data in this case.
Here's the myvignette.Rmd, in /vignettes
<!--
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Supplementary materials}
-->
```{r setup, message=FALSE, echo=FALSE}
library(knitr)
# This is necessary to direct knitr to find the
# 'data', and other directories that contain
# files needed to execute this document
# thanks to https://stackoverflow.com/a/24585750/1036500
opts_knit$set(root.dir=normalizePath('../'))
```
```{r}
library(mypackage)
myfunc()
```
```{r}
mydata <- read.csv("data/mycsv.csv", header = FALSE)
mydata
```
Here are the key bits of my example package (the rest is auto-generated by devtools::check and I haven't altered them):
DESCRIPTION
Package: mypackage
Title: What the package does (short line)
Version: 0.1
Authors#R: "First Last <first.last#example.com> [aut, cre]"
Description: What the package does (paragraph)
Depends:
R (>= 3.1.1)
License: MIT
LazyData: true
VignetteBuilder: knitr
Suggests:
knitr
R/myfunction.r
#' my function
#' An example function
#' #export
#'
my_func <- function() Sys.time()
R/docfordata.r
#' #title mycsv
#' #docType data
#' #keywords dataset
#' #format csv
#' #name mycsv
NULL
data/mycsv.csv
1,2,3
11,12,13
22,23,23
I'm working in RStudio 0.98.953, here's the session info
sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
other attached packages:
[1] mypackage_0.1
loaded via a namespace (and not attached):
[1] devtools_1.5 digest_0.6.4 evaluate_0.5.5
[4] httr_0.3 memoise_0.2.1 packrat_0.3.0.107
[7] parallel_3.1.1 Rcpp_0.11.2 RCurl_1.95-4.1
[10] roxygen2_4.0.1 stringr_0.6.2 tools_3.1.1
[13] whisker_0.3-2
UPDATE
Following Andrie's helpful comments I've moved my csv file to inst/extdata and put this line in the vignette read.csv(system.file("extdata/mycsv.csv", package="mypackage"), header = FALSE) and that allows my package to pass both devtools::check and devtools::build. But now it failsknitr::knit2html('vignettes/myvignette.Rmd') anddevtools::build_vignettes()` and at the console with the error messages:
For knit2html:
Quitting from lines 22-29 (vignettes/myvignette.Rmd)
Error in read.table(file = file, header = header, sep = sep, quote = quote, :
no lines available in input
For build_vignettes:
Building mypackage vignettes
Quitting from lines 22-29 (myvignette.Rmd)
Error: processing vignette 'myvignette.Rmd' failed with diagnostics:
no lines available in input
For read.csv(system.file("extdata/mycsv.csv", package = "mypackage"), header = FALSE)
Error in read.table(file = file, header = header, sep = sep, quote = quote, :
no lines available in input
In addition: Warning message:
In file(file, "rt") :
file("") only supports open = "w+" and open = "w+b": using the former
This must be something to do with the wandering inst/ directory that gets moved around when the package is built. So it's fair enough that knit2html and the console might not work, but surely build_vignettes should still work?
Also related: How do I refer to files in the inst directory of an R package from a script in the data directory?
To use a file in the vignette, you can add the file to the vignette folder.
An example of this is in the package tidyr at https://github.com/hadley/tidyr/blob/master/vignettes/tidy-data.Rmd
Try putting your csv file directly to the vignette folder

How to unload a package without restarting R

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?
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)
You can also use the unloadNamespace command, as in:
unloadNamespace("sqldf")
The function detaches the namespace prior to unloading it.
You can uncheck the checkbox button in RStudio (packages).
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)
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!
detach(package:PackageName) works and there is no need to use quotes.
Another option is
devtools::unload("your-package")
This apparently also deals with the issue of registered S3 methods that are not removed with unloadNamespace()
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
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)
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.
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)
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>

Resources