Check for installed packages in R - r

Based on the answer to this question: Elegant way to check for missing packages and install them?
I'm using the following code to make sure that all packages are installed when I upgrade R, or set up other users:
list.of.packages <- c("RODBC", "reshape2", "plyr")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
I've placed it in my .First function in my .Rprofile, but when I start up R it gives the following error and continues starting up:
Error in match(x, table, nomatch = 0L) :
could not find function "installed.packages"
If I run the code after I get a prompt it works fine. Any ideas why?
Thanks!

It appears from reading ?Startup that:
Next, if a function .First is found on the search path, it is executed
as .First(). Finally, function .First.sys() in the base package is
run. This calls require to attach the default packages specified by
options("defaultPackages").
Now, installed.packages is in the utils package, which is typically one of the default packages. So it's not available at the time .First is called.
Perhaps try replacing installed.packages with utils::installed.packages?
As Josh notes below my eyes skimmed over the piece that addresses this issue directly, namely:
Note that when the site and user profile files are sourced only the
base package is loaded, so objects in other packages need to be
referred to by e.g. utils::dump.frames or after explicitly loading the
package concerned.

Related

mmetric could not find function R

I have library(rminer) installed yet wondering why mmertric is still not there and unable to use the function.
Anyone has come across this?
#probability of each landmass category
flagdmodel <- naiveBayes(landmass ~ ., data=trainfdata)
#flagdmodel
#predictionmodel
flagprediction <- predict(flagdmodel, testfdata)
mmetric(testfdata$landmass, flagprediction, c("ACC","PRECISION","TPR","F1"))
+ mmetric(testfdata$landmass, flagprediction, c("ACC","PRECISION","TPR","F1"))
mmetric()
Error in mmetric() : could not find function "mmetric"
mmetric()
Error in mmetric() : could not find function "mmetric"
Question: why can't R find functions for the package I installed with RStudio's install tool?
Answer:
When you want to use functions or other objects in packages that aren't in R, you need to do two things:
install.packages("rminer")
library(rminer)
RStudio can do the first step for you with the install tool, but you still need to do the second one. The first step installs the needed directories and files on your computer. The second step loads them into your current R environment.
In RStudio, you can use the packages tab to check both steps. Installed packages will be in the list in that tab. Loaded packages will have a checkmark to the left of the package name.
It may be easier to find, though if you just run the following in your console:
"package:rminer" %in% search()
If the output is TRUE you're good to go. If it's FALSE you need to run library(rminer)

How to use a platform specific package in my R function

my R package has a function (my_func) that uses function(bar) from another package (foo) which only available on Unix. So I write my code this way, following the suggested packages in Writing R extension:
my_func = function(){
....
if (requireNamespace("foo", quietly = TRUE)) {
foo::bar(..) # also tried bar(...)
} else {
# do something else without `bar`
}
...
}
However, I keep getting such warning message when I run R CMD check:
'loadNamespace' or 'requireNamespace' call not declared from: foo
Is there any way to use platform specific packages without gives such warnings? I tried to include foo in the Description file and the warning disappeared, but then the package cannot be installed on windows because foo is not available for the win.
I think you misread that comment, though it is easy to do because the logic is not clear and incontrovertible.
In that first paragraph that talked about calling packages using require(package) they said it was OK for a test environment or vignette but not from inside a finished function to use library(package) or require(package).
This is considered bad form, because the packages you call inside a function will usurp the order of access your user has set up in her work environment when loading packages.
The method you use above:
package::function()
is the approved of way to use a function within a function without altering the current environment.
But in order to use that function you must still have that package installed on your current machine or in your current working environment (such as a virtualenv or ipython or jupytr..and yes R will work in all those environments).
You cannot run a function that R cannot see from the working environment...so you must have it installed, but not necessarily loaded, to call it.

How can I find where the package I loaded comes from

I want to programatically save some packages my script has loaded (I mean the actual directory).
I know doing .libPaths() shows the paths where the packages can come from (though I could also load it from somewhere different).
Is there an already build function to get where a package that I loaded comes from ?
My solution would be:
sess.info <- sessionInfo()
names.packages <- names(sess.info$loadedOnly)
find.package(names.packages)
I hope this is what you are searching for.

How can I install packages in knitr?

Till now, I was using this chunk of code to load R packages and write .R files. But I am trying to use knitr
rm (list=ls(all=TRUE))
kpacks <- c('ggplot2','install_github','devtools','mapdata')
new.packs <- kpacks[!(kpacks %in% installed.packages()[,"Package"])]
if(length(new.packs)) install.packages(new.packs)
lapply(kpacks, require, character.only=T)
remove(kpacks, new.packs)
options(max.print=5.5E5)
But now, when I put this chunk of code in a Knitr document, I get this error:
Error in contrib.url(repos, "source") :
trying to use CRAN without setting a mirror calls:......
How can I fix this?
The narrow answer to your question is that you should set your repos option:
options(repos=c(CRAN="<something sensible near you>"))
You're hitting the problem because R's default behaviour when the repository option is initially unset is to query the user -- and it can't do that when you're running code non-interactively.
More broadly, I would question whether you want to include this sort of thing in your R code; under some circumstances it can be problematic.
what if the user doesn't have a network connection?
what if they are geographically very far from you so that your default repository setting doesn't make sense?
what if they don't feel like downloading and installing a (possibly large) package?
My preferred practice is to specify in the instructions for running the code that users should have packages X, Y, Z installed (and giving them example code to install them, in case they're inexperienced with R).
One way to avoid installing the packages is to do something like
if(!require(package.name))
stop("you need to install package.name")
In your code chunk. Depending on your knitr document settings, this will generate the message in the document, in the console, or prevent the document from being knitted.

R suppress startupMessages from dependency

One of my R package's dependencies displays startup messages when loaded. I would like to suppress these startup messages.
The only fix I found so far was removing the offending package from the Depends: line in my DESCRIPTION file. Then calling suppressPackageStartupMessages(require("offendingPackage")) in .onLoad of my package.
I would rather keep the offending package as part of my Depends, but it seems that anything specified in depends is automatically loaded and therefore can't be supressed.
The suppressPackageStartupMessages() function works if and only if the startup messages are actually written with packageStartupMessage() -- see the help page.
Many packages just use cat(), which one could consider a buglet. In that case
suppressMessages(library(foo))
works better.
If you work with namespaces, you can specify the package in Imports, and load the necessary functions using import or importFrom. This way, the package is not attached, but the necessary functions can be loaded and used by your package. Without attaching, the startup messages are not given, so this approach assures you won't see any startup messages of packages specified in Imports.
Make sure you check that you imported everything that is of importance. If the package you import is dependent on other packages, I'm not sure everything you need to use those functions is imported. You might have to do a bit of puzzling to get everything you need loaded. On the plus side, using Imports assures that any dependencies check will be carried out correctly.
Another option is to not specify the package in Depends, but in Suggests in the DESCRIPTION file, and use the option #Dirk gave you. This will give a correct dependency check if 'dependencies=TRUE' is set in install.packages(). But personally I think using the namespaces is a lot more clean.
A quick hack to do this inline in a script or environment is to override library()/require() to wrap the suppressPackageStartupMessages() method:
> library(here) # This shows a message
here() starts at /home/z/development/
> require(here) # This shows a message
Loading required package: here
here() starts at /home/y
The workaround:
> flibrary <- library
> library <- function(...) suppressPackageStartupMessages(flibrary(...))
> library(here) # No messages
>
> frequire <- require
> require <- function(...) suppressPackageStartupMessages(frequire(...))
> require(here) # No messages
>

Resources