Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use functions from other packages in a R package

Tags:

I am a bit confused about this. I have an R package that has a small function (not a mayor part of the package) in which the principal function of the psych package is called. How do I correctly specify this in DESCRIPTION and NAMESPACE?

Setting Depends: psych in DESCRIPTION makes sure the psych package is loaded every time my package is loaded. This works, but it seems redundant for such a small part of my package.

Setting Suggests: psych and entering a require("psych") in the function is what I do now, however this does not work if psych is not installed, and seems to be the wrong way of doing this (writing R extensions says that suggest is meant mainly for examples).

I think I need to import the function. I tried setting Imports: psych in DESCRIPTION and importFrom(psych,"principal") in NAMESPACE. This works, but on a computer that does not has psych installed it gives an error when loading my package.

like image 506
Sacha Epskamp Avatar asked Mar 10 '11 13:03

Sacha Epskamp


People also ask

How do you call a function from a package in R?

Every time you start a new R session you'll need to load the packages/libraries that contain functions you want to use, using either library() or require() . If you load a package with the same function name as in another package, you can use packageName::functionName() to call the function directly.

Which package contains functions for installing other R packages?

Packages for R can be installed from the CRAN package repository using the install. packages function. This function will download the source code from on the CRAN mirrors and install the package (and any dependencies) locally on your computer.

How do you access data from an R package?

If you look at the package listing in the Packages panel, you will find a package called datasets. Simply check the checkbox next to the package name to load the package and gain access to the datasets. You can also click on the package name and RStudio will open a help file describing the datasets in this package.


1 Answers

The basic question you need to answer is: "do you want the function to be available to all users of the package without further effort?". If yes, then use imports + the appropriate namespace declarations, if no, then use suggests and print an informative error message if require("psych") returns FALSE.

I don't understand your import related complaint that: "but on a computer that does not has psych installed it gives an error when loading my package". This is also true if your package is in depends!

like image 199
hadley Avatar answered Oct 30 '22 23:10

hadley