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

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)

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>

R: Evaluating a script in an environment

I would like to load a library function within a script evaluated in a specified environment.
Example:
## foo.R
## -----
## blah blah
library(extrafont)
loadfonts()
Assuming for convenience the evaluation environment is the base environment:
sys.source("foo.R")
## Registering fonts with R
## Error in eval(expr, envir, enclos) : could not find function "loadfonts"
Replacing loadfonts() with extrafont:::loadfonts() works better, but still gives:
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'pdfFonts' of mode 'function' was not found
because loadfonts() requires pdfFonts() defined in grDevices.
This is both a not totally satisfactory answer and a long comment to #waterling.
The proposed solution is:
e<- new.env()
source("foo.R", local=e)
i.e.
source("foo.R", local=new.env())
which is substantially equivalent to:
sys.source("foo.R", envir=new.env())
It works for much the same reason why:
sys.source("foo.R", envir=as.environment("package:grDevices"))
As reported in the error (see question), the function not found, pdfFonts() is part of the package grDevices The sys.source above executes the script in the package:grDevices environment, hence the function is found. Instead by default sys.source(..., envir=baseenv()) and the base environment comes before grDevices, therefore pdfFonts() is not found.
A first problem is that I do not know in advance which functions will happen to be in my script.
In this case setting envir=new.env() is a more general approach. By default
new.env(parent=parent.frame()),
therefore it has the same parent of sys.source(), which is the global environment. So everything visible in the global environment is visible in the script with sys.source(..., envir=new.env()), that is every object created by the user and by the user loaded packages.
The problem here is that we are not insulating the script any more, which makes it less reproducible and stable. In fact, it depends on what is in R memory in the very moment we call sys.source.
To make the things more practical, it means foo.R might work just because we usually call it after bar.R.
A second problem is that this not an actual solution.
The question concerns how to run a script foo.R in an environment e and still access, when needed, to functions not belonging to e. Taking an e that (directly or through its parents) has access to these functions is actually a workaround, not a solution.
If this type of workaround is the only possible way to go, IMHO, the best is to make it dependent only on standard R packages.
At start, R shows:
search()
## [1] ".GlobalEnv" "package:stats" "package:graphics"
## [4] "package:grDevices" "package:utils" "package:datasets"
## [7] "package:methods" "Autoloads" "package:base"
that is eight official packages/environments.
New packages/environments, unless explicitly changing the default, go into the second slot and all those after the first one shift one position.
myEnv=new.env()
attach(myEnv)
search()
## [1] ".GlobalEnv" "myEnv" "package:stats"
## [4] "package:graphics" "package:grDevices" "package:utils"
## [7] "package:datasets" "package:methods" "Autoloads"
## [10] "package:base"
So we can take the last eight in the search path, which means taking the first of these eight inheriting the others. We need:
pos.to.env(length(search()) - 7)
## <environment: package:stats>
## attr(,"name")
## [1] "package:stats"
## attr(,"path")
## [1] "path/to//R/R-x.x.x/library/stats"
Therefore:
sys.source("foo.R", envir=new.env(parent=pos.to.env(length(search()) - 7)))
or one can take a standard R reference package, say stats, and its parents.
Therefore:
sys.source("foo.R", envir=new.env(parent=as.environment("package:stats")))
UPDATE
I found the
SOLUTION
As for the script:
#foo.R
#-----
library(extrafont)
f=function() loadfonts()
environment(f) = as.environment("package:extrafont")
f()
To execute in a new environment:
sys.source("foo.R", envir=new.env(parent=baseenv()))
f() now has access to all objects in the package extrafont and those loaded before it.
In sys.source() creating a new.env() with whatever parent is necessary to make environment() assignment work.

Error in XLConnect

I am trying to import an excel sheet into r. I used the following code:
x <- loadWorkbook("x.xlsx")
b <- readWorksheet(x, sheet="b")
The first line works fine, however, running the second gives the following error:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘readWorksheet’ for signature ‘"jobjRef", "character"’
I have no missing values in that sheet.
For the purpose of reproducing, download trial.xlsx from https://github.com/ahmedfsalhin/1stpaper.
system info: Yosemite operating system.
It appears the "root cause" is that you should add code to specify both the function and the package it belongs to. Type XLConnect::loadWorkbook to select the one you want in this case. There's no 'confusion,' or random selection of duplicated function names in R. The choice depends on the load order of all loaded packages. Use search() to see the order in which packages are checked for the command you've entered.
E.g., at present I get
search()
[1] ".GlobalEnv" "package:caTools"
[3] "package:XLConnect" "package:XLConnectJars"
[5] "package:stats" "package:graphics"
[7] "package:datasets" "package:vecsets"
[9] "package:cgwtools" "package:grDevices"
[11] "package:utils" "package:methods"
[13] "Autoloads" "package:base"
You'll notice that anything in your environment (.GlobalEnv) is selected first, and that all loaded libraries override the base package, for example.
After lot of struggle found the solution to this. In R studio go to the packages and remove all the packages related to XLConnect and xlsx. Then instal only XLConnect packages by typing
install.packages("XLConnect", dependencies=TRUE)
After this the issue should not exist.
I had the same problem while testing out three different packages for loading .xlsx files into R (XLConnect, xlsx, gdata). The solution was to specify the namespace for loadWorkbook:
d3_wb = XLConnect::loadWorkbook("Megadataset_v3.xlsx")
d3 = readWorksheet(d3_wb, 1)
Then it works, no matter if xlsx is loaded/installed or not. The error is because there is also a function with the same name in xlsx and it is defaulting to using the wrong one, which depends on the order the packages were loaded.
Try this instead
x <- readWorksheetFromFile("x.xlsx") in XLConnenct package.

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>

Getting the contents of a library interactively in R

Is there an equivalent of dir function (python) in R?
When I load a library in R like -
library(vrtest)
I want to know all the functions that are in that library.
In Python, dir(vrtest) would be a list of all attributes of vrtest.
I guess in general, I am looking for the best way to get help on R while running it in ESS on linux. I see all these man pages for the packages I have installed, but I am not sure how I can access them.
Thanks
help(package = packagename) will list all non-internal functions in a package.
Yes, use ls().
You can use search() to see what's in the search path:
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
You can search a particular package with the full name:
> ls("package:graphics")
[1] "abline" "arrows" "assocplot" "axis"
....
I also suggest that you look at this related question on stackoverflow which includes some more creative approaching to browsing the environment. If you're using ESS, then you can use Ess-rdired.
To get the help pages on a particular topic, you can either use help(function.name) or ?function.name. You will also find the help.search() function useful if you don't know the exact function name or package. And lastly, have a look at the sos package.
help(topic) #for documentation on a topic
?topic
summary(mydata) #an overview of data objects try
ls() # lists all objects in the local namespace
str(object) # structure of an object
ls.str() # structure of each object returned by ls()
apropos("mytopic") # string search of the documentation
All from the R reference card

Resources