dependent packages not loading in R on Debian - r

I'm having trouble loading the sde package on a clean Debian install running R 2.11.1. I've seen this behavior with some other packages, however, so I don't think it's specific to only this one package. Here's an example of the conundrum:
>install.packages("sde", lib.loc=libPath)
... installs sde, and the packages it's dependent on: zoo, fda
> library(sde, lib=libPath)
Loading required package: fda
Error: package 'fda' could not be loaded
In addition: Warning message:
In library(pkg, character.only = TRUE, logical.return = TRUE, lib.loc = lib.loc) :
there is no package called 'fda'
ok, that's odd. I saw fda being installed. So I manually load the dependencies:
> library(zoo, lib=libPath)
> library(fda, lib=libPath)
Loading required package: splines
ok, that worked. Now let's try sde:
> library(sde, lib=libPath)
To check the errata corrige of the book, type vignette("sde.errata")
WTF? it loaded fine?!?
So why can I manually load the packages but R is not picking them up automagically?
Adding to my confusion, I discovered during debugging that if I don't use the lib=libPath then everything works just fine. So it looks like the use of a custom path for packages is screwing this all up... but why?

You confirmed my suspicions in the comments. You need to do one of two things:
.libPaths(libPath)
or
library(sde, lib=c(libPath,.libPaths()))
I prefer the first method because the second requires you do that for all calls to library.

Related

How to import sf to package to run a function that depends on lwgeom?

I'm building a package that imports {sf}, and more specifically I use st_length() in one of my functions.
I initially added only {sf} to my package "Imports", but when I checked it I got a few {lwgeom} related errors:
Running examples in 'gtfstools-Ex.R' failed
The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: get_trip_speed
> ### Title: Get trip speed
> ### Aliases: get_trip_speed
>
> ### ** Examples
>
> data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")
>
> gtfs <- read_gtfs(data_path)
>
> trip_speed <- get_trip_speed(gtfs)
Error in sf::st_length(trips_geometries) :
package lwgeom required, please install it first
This error happens when the examples are running, but some similar errors happen with the tests.
Then I added {lwgeom} to Imports. The check runs fine, but in the end I get a note: NOTE: Namespaces in Imports field not imported from: 'lwgeom'
What's the best practice when dealing with cases like this? Should I just keep track of this note and send it as a comment to CRAN during the package submission process?
You can consider adding the {lwgeom} package in Suggests field of your package DESCRIPTION file. It should do the trick.
The Suggests != Depends article by Dirk Eddelbuettel refers to a relevant bit of Writing R Extensions (WRE) that might be useful to this case.
Section 1.1.3.1 (suggested packages) reads (as of 2021-03-12):
Note that someone wanting to run the examples/tests/vignettes may not have a suggested package available (and it may not even be possible to install it for that platform). The recommendation used to be to make their use conditional via if(require("pkgname")): this is OK if that conditioning is done in examples/tests/vignettes, although using if(requireNamespace("pkgname")) is preferred, if possible.
However, using require for conditioning in package code is not good practice as it alters the search path for the rest of the session and relies on functions in that package not being masked by other require or library calls. It is better practice to use code like
if (requireNamespace("rgl", quietly = TRUE)) {
rgl::plot3d(...)
} else {
## do something else not involving rgl.
}
So while just adding {lwgeom} to Suggests works, we may stumble upon the issue where someone that runs a "lean installation" (i.e. without suggested packages) of my package won't be able to use the functions that rely on {lwgeom}.
More importantly, if an author of a package that I am importing decides to run a reverse dependency check on my package while not installing suggested packages, the check would fail because I'd have a few examples, tests and vignettes bits failing due to not having {lwgeom} available.
Thus, in addition to listing it in Suggests, I added some checks on examples and vignettes like suggested by WRE:
*examples/vignette context*
# the examples below require the 'lwgeom' package to be installed
if (requireNamespace("lwgeom", quietly = TRUE)) {
... do something ...
}
In the functions that require {lwgeom} I added:
if (!requireNamespace("lwgeom", quietly = TRUE))
stop(
"The 'lwgeom' package is required to run this function. ",
"Please install it first."
)
And added this bit to the tests of such functions (using {testthat}):
if (!requireNamespace("lwgeom", quietly = TRUE)) {
expect_error(
set_trip_speed(gtfs, "CPTM L07-0", 50),
regexp = paste0(
"The \\'lwgeom\\' package is required to run this function\\. ",
"Please install it first\\."
)
)
skip("'lwgeom' package required to run set_trip_speed() tests.")
}

R CHECK WARNING: Requires Orphaned Package

Recently I built an R package and wanted to publish it in CRAN. I had checked it in my local machine (WIN10 R>=3.6) and it showed there was 0 WARNING, 0 NOTE and 0 ERROR. Then I uploaded it to the CRAN. However, the CRAN CHECK showed that I had one WARNING in LINUX: here is the raw log.
Flavor: r-devel-linux-x86_64-debian-gcc
Check: package dependencies, Result: WARNING
Requires orphaned package: 'flare'
The package flare is in the "Imports". I checked the R POLICIES and found it said "Orphaned CRAN packages should not be strict requirements". However, if I change the dependency to "Suggests", I cannot use the function slim in the package flare. How can I adjust it so that I can pass the CRAN CHECK?
The standard use of a package in Suggests: is to test it before you use it. So for a function bar() from package foo, change your code from
res <- bar(a,b,c) # foo in NAMESPACE as imports
to
res <- NA
if (requireNamespace("foo", quietly=TRUE) {
res <- foo::bar(a,b,c) # package foo in Suggests
} else {
warning("Would need foo for bar") # message optional
}
There is no other way to appease the CRAN check. (Besides adopting the orphaned package but that is a whole different ball game.)

how to add new R packages in azure machine learning for time series anomaly detection

I am trying to find out time series anomaly detection in which i need to install new R packages. In this i m following https://github.com/business-science/anomalize site. In this i needed to install 2 packages: tidyverse and anomalize.
can anyone help me on installing package mentioned above as I am getting
error "package or namespace load failed for tidyverse"
Also while adding zip of tidyverse and anomalize do I need to add any other packages and dependencies in that as I am adding only those 2 packages thinking there r no other dependencies I needed for those 2?
you can see in code that I created R_Package.zip and put tidyverse.zip and anomalize.zip in that that
dataset1 <- maml.mapInputPort(1)
data.set <- data.frame(installed.packages())
#install.packages(“src/R_Package/tidyverse_1.2.1.zip”, lib = “.”,
repos = NULL, verbose = TRUE);
#library(tidyverse, lib.loc=”.”, verbose=TRUE);
install.packages("src/tidyverse.zip",lib=".",repos=NULL,verbose=TRUE)
library(R_package, lib.loc = ".", verbose=TRUE);
install.packages("src/anomalize.zip",lib=".",repos=NULL,verbose=TRUE)
library(R_package, lib.loc = ".", verbose=TRUE);
#success <- library("tidyverse", lib.loc = ".",
logical.return = TRUE, verbose = TRUE)
#library(tidyverse)
maml.mapOutputPort("dataset1");
Regarding the error message, notice that it may take some time for the installed packages to become actually available; quoting from Adding R Packages In Azure ML blog post:
Note: In one instance, we ran into an issue where the package was not
loaded into the workspace immediately. We had to wait about half an
hour before we could use the package. You may be running into this
issue as well if you see a message that looks something like this
and you’ve used the above method to check which packages are in your
workspace and the package in question appears on that list. If this is
the case, we suggest waiting a bit before running your experiment
again.
AFAIK yes, you also need to add the package dependencies; the SO thread Install R Packages in Azure ML contains some useful hints.

R - How Do I Force Installation of My Custom Package to Fail When Imported Package Version is Too Old?

I've been working on a custom R library at work. I use functions from a couple different packages (always qualified with ::), so I've added them to the Imports section of my DESCRIPTION file. When I use R CMD INSTALL to install my package, I get a warning if the version of an imported package is too old, but installation continues. How do I force it to fail and alert the user that they need to update that package? I don't want to add any of them to the Depends section because I don't want those extra packages loaded when my library is loaded.
Example DESCRIPTION file:
Depends:
R (>= 3.1.2)
Imports:
dplyr (>= 0.7.0)
If dplyr 0.5.0 is loaded on the user's system, installation continues, but certain functions that depend on dplyr 0.7.0 will fail when called.
Here is a possible solution using find.package, packageDescription and packageVersion:
.onLoad <- function(libname, pkgname) {
myImports <- strsplit(utils::packageDescription(pkgname)[["Imports"]], split = ",\\s")[[1]]
if (length(find.package("dplyr", quiet = TRUE)) > 0) {
reqVers <- grep("^dplyr [(]", myImports, value = TRUE)
reqVers <- sub("^dplyr [(]>= ([0-9]+.*[0-9]+).*", "\\1", reqVers)
if (check <- utils::packageVersion("dplyr") < reqVers)
stop("Dplyr is version ", utils::packageVersion("dplyr"), " --- this package requires version ", reqVers, " at least")
}
invisible()
}
Like you say in the comment, common practice is to put this into a file called zzz.R.
Of course you could also replace the stop with a warning.

Check if R package is installed then load library

Our R scripts are used on multiple users on multiple computers and hence there are deviations in which packages are installed on each computer. To ensure that each script works for all users I would like to define a function pkgLoad which will first test if the package is installed locally before loading the library with suppressed startup messages. Using Check for installed packages before running install.packages() as a guide, I tried
pkgLoad <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE, repos='http://star-www.st-andrews.ac.uk/cran/')
if(!require(x,character.only = TRUE)) stop("Package not found")
}
#now load library and suppress warnings
suppressPackageStartupMessages(library(x))
library(x)
}
When I try to load ggplot2 using pkgLoad("ggplot2") I get the following error message in my terminal
Error in paste("package", package, sep = ":") :
object 'ggplot2' not found
> pkgLoad("ggplot2")
Loading required package: ggplot2
Error in library(x) : there is no package called ‘x’
> pkgLoad("ggplot2")
Error in library(x) : there is no package called ‘x’
Any why x changes from ggplot2 to plain old x?
I wrote this function the other day that I thought would be useful...
install_load <- function (package1, ...) {
# convert arguments to vector
packages <- c(package1, ...)
# start loop to determine if each package is installed
for(package in packages){
# if package is installed locally, load
if(package %in% rownames(installed.packages()))
do.call('library', list(package))
# if package is not installed locally, download, then load
else {
install.packages(package)
do.call("library", list(package))
}
}
}
The CRAN pacman package that I maintain can address this nicely. Using the following header (to ensure pacman is installed first) and then the p_load function will try to load the package and then get them from CRAN if R can't load the package.
if (!require("pacman")) install.packages("pacman"); library(pacman)
p_load(qdap, ggplot2, fakePackage, dplyr, tidyr)
Use library(x,character.only=TRUE). Also you don't need the last line as suppressPackageStartupMessages(library(x,character.only=TRUE)) already loads the package.
EDIT: #LarsKotthoff is right, you already load the package inside of the if brackets. There you already use option character.only=TRUE so everything is good if you just remove last to lines of your function body.
Have a look at this nice function:
klick
The following can be used:
check.and.install.Package<-function(package_name){
if(!package_name%in%installed.packages()){
install.packages(package_name)
}
}
check.and.install.Package("RTextTools")
check.and.install.Package("e1071")
Though #maloneypatr function works fine, but it is quite silent and does not respond on success of packages loaded. I built below function that does make some checks on user entry and also respond on the number of packages being successfully installed.
lubripack <- function(...,silent=FALSE){
#check names and run 'require' function over if the given package is installed
requirePkg<- function(pkg){if(length(setdiff(pkg,rownames(installed.packages())))==0)
require(pkg, quietly = TRUE,character.only = TRUE)
}
packages <- as.vector(unlist(list(...)))
if(!is.character(packages))stop("No numeric allowed! Input must contain package names to install and load")
if (length(setdiff(packages,rownames(installed.packages()))) > 0 )
install.packages(setdiff(packages,rownames(installed.packages())),
repos = c("https://cran.revolutionanalytics.com/", "http://owi.usgs.gov/R/"))
res<- unlist(sapply(packages, requirePkg))
if(silent == FALSE && !is.null(res)) {cat("\nBellow Packages Successfully Installed:\n\n")
print(res)
}
}
Note 1:
If silent = TRUE(all capital silent), it installs and loads packages without reporting. If silent = FALSE, it reports successful installation of packages. Default value is silent = FALSE
How to use
lubripack(“pkg1","pkg2",.,.,.,.,"pkg")
Example 1: When all packages are valid and mode is not silent
lubripack(“shiny","ggvis")
or
lubripack(“shiny","ggvis", silent = FALSE)
Output
Example 2: When all packages are valid and mode is silent
lubripack(“caret","ggvis","tm", silent = TRUE)
Output 2
Example 3: When package cannot be found
lubripack(“shiny","ggvis","invalidpkg", silent=FALSE)
Output 3
How to Install Package:
Run below code to download the package and install it from GitHub. No need to have GitHub Account.
library(devtools)
install_github("espanta/lubripack")

Resources