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>
Related
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>
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)
While using the Boot function from the car package I get the error message
Error in get(".y.boot", envir = .carEnv) : object '.carEnv' not found
I suspect I have inadvertently changed/set something in my OS and have no idea what it might be. Running the code below returns an error on my desktop but runs without error on a laptop running the same OS (Yosemite) as well as a desktop running Windows 7 (all using R-3.1.2). The code that triggers the message is
library(car)
swiss.lm <- lm(Fertility ~ Education, data = swiss)
BC <- Boot(swiss.lm, R = 999, method = "case") # No Problems
BR <- Boot(swiss.lm, R = 999, method = "residual") # Problems now
Error in get(".y.boot", envir = .carEnv) : object '.carEnv' not found
I have reinstalled R but the error still appears when running the above code. Any suggestions as to what I have done and how to get the code to run and find the environment would be most appreciated. TIA!
> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-apple-darwin13.4.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] stats graphics grDevices utils datasets methods base
other attached packages:
[1] car_2.0-24
loaded via a namespace (and not attached):
[1] boot_1.3-15 grid_3.1.2 lattice_0.20-29 lme4_1.1-7 MASS_7.3- 37 Matrix_1.1-5
[7] mgcv_1.8-4 minqa_1.2.4 nlme_3.1-119 nloptr_1.0.4 nnet_7.3-9 parallel_3.1.2
[13] pbkrtest_0.4-2 quantreg_5.11 Rcpp_0.11.4 SparseM_1.6 splines_3.1.2 tools_3.1.2
Looks like a reproducible bug in a car package. According to package news the changes in latest version (2.0-24) are related to .carEnv handling.
I tried to get around the issue by simply assigning the .carEnv before call to Boot with
.carEnv <- car:::.carEnv
This makes the Boot function execute without errors, but I am not sure of any other effects.
The package maintainer emailed me and indicated a bug had been introduced in 2.0-24 and that he would attempt to fix the bug.
When I create s3 methods in R 2.14.1, and then call them, the s3 objects fail to execute the methods in cases where the method has the same name as functions already loaded into the workspace (i.e. base functions). Instead it calls the base function and returns an error. This example uses 'match'. I never had this problem before today. Since I last ran this code, I installed R 3.0.2, but kept my 2.14.1 version. I ran into some trouble (different trouble) with 3.0.2 due to certain packages not being up to date in CRAN, so I reverted RStudio to 2.14.1, and then this problem cropped up. Here's an example:
rm(list=ls())
library(R.oo)
this.df<-data.frame(letter=c("A","B","C"),number=1:3)
setConstructorS3("TestClass", function(DF) {
if (missing(DF)) {
data= NA
} else {
data=DF
}
extend(Object(), "TestClass",
.data=data
)
})
setMethodS3(name="match", class="TestClass", function(this,letter,number,...){
ret = rep(TRUE,nrow(this$.data))
if (!missing(number))
ret = ret & (this$.data$number %in% number)
if (!missing(letter)){
ret = ret & (this$.data$letter %in% letter)
}
return(ret)
})
setMethodS3("get_data", "TestClass", function(this,...) {
return(this$.data[this$match(...),])
})
hope<-TestClass(this.df)
hope$match()
Error in match(this, ...) : argument "table" is missing, with no default
hope$get_data()
Here's the sessionInfo() for clues:
sessionInfo()
R version 2.14.1 (2011-12-22)
Platform: i386-pc-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] R.oo_1.13.0 R.methodsS3_1.4.2
loaded via a namespace (and not attached):
[1] tools_2.14.1
I tried a lot of combinations of the arguments in setMethodsS3 with no luck.
How can I fix this?
First, I highly recommend calling S3 methods the regular way and not via the <object>$method(...) way, e.g. match(hope) instead of hope$match(). If you do that, everything works as expected.
Second, I can reproduce this issue with R 3.0.2 and R.oo 1.17.0. There appears to be some issues using the particular method name match() here, because if you instead use match2(), calling hope$match2() works as expected. I've seen similar problems when trying to create S3 methods named assign() and get(). The latter actually generates a error if tried, e.g. "Trying to use an unsafe generic method name (trust us, it is for a good reason): get". I'll add assign() and most likely match() to the list of no-no names. DETAILS: Those functions are very special in R so one should avoid using those names. This is because, if done, S3 generic functions are created for them and all calls will be dispatched via generic functions and that is not compatible with
Finally, you should really really update your R - it's literally ancient and few people will not bother trying to help you with issues unless you run the most recent stable R version (now R 3.0.2 soon to be R 3.1.0). At a minimum, you should make sure to run the latest versions of the package (your R.methodsS3 and R.oo versions are nearly 2 and 1 years old by now with important updates since).
Hope this helps
I have experiencing a weird problem with the 'plot' function of the 'raster' package.
library(raster)
ras <- raster(ncol=10, nrow=10)
EDIT
values(ras) <- runif(ncell(ras))
END EDIT
plot(ras)
Erreur dans as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
For what I have read on the net, this error depends on the user, and probably depends on the loaded packages. In my case, the problem comes from the fact that r uses the standard 'plot' method from the 'graphics' package, when it should use the specific 'raster' method since 'ras' is a rasterLayer object. However, for a reason I do not understand, 'plot' is not imported in the 'raster' namespace, while all the other functions are.
> raster::plot
Erreur : 'plot' n'est pas un objet exporté depuis 'namespace:raster'
To be compared with :
raster::persp
standardGeneric for "persp" defined from package "graphics"
function (x, ...)
standardGeneric("persp")
<environment: 0x0cd9eb80>
Methods may be defined for arguments: x
Use showMethods("persp") for currently available ones.
Since I do not completely understand how namespaces behave, I am looking for your help ! Is this kind of situation familiar for you, and do you have a way to solve it ? In the meantime, do you know a function to display the content of a namespace (so I could check the content of the raster namespace step by step) ?
PS: I am using R 2.15.2 with RStudio, many packages loaded but all are up to date.
sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: i386-pc-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=French_Belgium.1252 LC_CTYPE=French_Belgium.1252 LC_MONETARY=French_Belgium.1252 LC_NUMERIC=C
[5] LC_TIME=French_Belgium.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] raster_2.0-41 sp_1.0-5
loaded via a namespace (and not attached):
[1] grid_2.15.0 hexbin_1.26.0 intervals_0.13.3 lattice_0.20-6 rgdal_0.8-4 spacetime_1.0-3 spam_0.29-2 tools_2.15.0
[9] xts_0.9-2 zoo_1.7-9
Thanks you,
François
Using this you get all the list of object of package raster
basevals <- ls(pos="package:raster")
for example
which(basevals == 'persp') ## function persp shows up because it is the exported generic.
141
which(basevals == 'plot') ## no function plot
integer(0)
No when I do this , it works for me:
library(raster)
r <- raster(ncol=10, nrow=10)
values(r) <- runif(ncell(r))
plot(r, main='Raster with 100 cells')
So There is certainly a plot method here. It is not in the previous list "basevals" beacuse it is an S4 method.
To get the plot method of raster package , try this :
getMethod('plot',signature=signature(x='Raster', y='ANY'))
or more efficiently using
findMethods("plot", "package:raster").
This sometimes happens when you have a stale session (typically caused by loading an old session at startup), that goes away if you start a fresh R session (without loading previously saved sessions).
I had the same problem and re-installing the raster package fixed it.
install.packages("raster")
For me, what resolved this S4 class namespace issue was to add the raster package as a Dependency. Hence, using the attach() function should also work, as that is what dependencies do. I know that is not an ideal solution, but hey, it's a statistics language ;)
I've been running in the same error, also using RStudio.
My issues was that I loaded the raster package via library(raster) in the .Rprofile file of my project. But code in Rprofile gets loaded before anything else, so the graphics package (containing the plot generic) is loaded after raster, causing the problems.
Solution: Put library(graphics) before library(raster) in Rprofile, and it worked for me.