Writing an R-package I use name spaces to use functions from existing packages, e.g. raster::writeRaster(...).
However, I am wondering if functions from the base package have also be used like this, e.g. base::sum(...). This might end up in very confusing code parts:
foo[base::which(base::sapply(bar, function())]
No you don't need to reference base packages like this. You only need to reference non-base packages to ensure they are loaded into the function environment when functions from your package are run, either by using :: or #import in the Roxegen notes at the top of your script. See why you don't need to reference base packages below:
http://adv-r.had.co.nz/Environments.html
"Package namespaces keep packages independent. For example, if package A uses the base mean() function, what happens if package B creates its own mean() function? Namespaces ensure that package A continues to use the base mean() function, and that package A is not affected by package B (unless explicitly asked for)."(Hadley Wickham)
The only time you need to reference base:: is if the namespace for your package contains a package that has an alternative function of the same name.
Related
My goal is to create R package which use other library such as grid and ggplot2.
According to
https://tinyheero.github.io/jekyll/update/2015/07/26/making-your-first-R-package.html, it is said that library() or require() should not be used in a R package.
My questions are:
1)Is there a reason? (because, although I put library("ggplot2") and library("grid") in my R script in my package, it still worked).
2)Do I have to delete library("ggplot2") and library("grid") in my code and put "::" such as ggplot2::geom.segment()?
Is there an efficient way to convert script to the one for package?
You should never use library() or require() in a package, because they affect the user's search list, possibly causing errors for the user.
For example, both the dplyr and stats packages export a function called filter. If a user had only library(stats), then filter would mean stats::filter, but if your package called library(dplyr), the user might suddenly find that filter means dplyr::filter, and things would break.
There are a couple of alternatives for your package. You can import functions from another package by listing it in the Imports: field in the DESCRIPTION file and specifying the imports in the NAMESPACE file. (The roxygen2 package can make these changes for you automatically if you put appropriate comments in your .R source files, e.g.
#' #importFrom jsonlite toJSON unbox
before a function that uses those to import toJSON() and unbox() from the jsonlite package.)
The other way to do it is using the :: notation. Then you can still list a package in the Imports: field of DESCRIPTION, but use code like
jsonlite::toJSON(...)
every time you want to call it. Alternatively, if you don't want a strong dependence on jsonlite, you can put jsonlite in Suggests:, and wrap any uses of it in code like
if (requireNamespace("jsonlite")) {
jsonlite::toJSON(...)
}
Then people who don't have that package will still be able to run your function, but it may skip some operations that require jsonlite.
I built my own package. I imported the most important package that I need them in my package. In these packages there are some functions are not exported by the package (I did not find them in the namespace of the package). I need these functions. When I call them, I get an error that those funciton are not found. So, How I can solve this problem. Also, how does these packages uses this functions inside their packages without using #export!! any help please?
based on the answer:
I understand I do it like this inside my R code: I need the following function:
args <- preproc(c(as.list(environment()), call = match.call()),
check_matrix,
check_fammat,
check_parmat,
check_par2mat)
list2env(args, environment())
Then I must do like this:
VineCopula:::preproc()
Then how to call args?
You can call non exported functions with
packagename:::functionname()
It is however not recommended to do that since those functions might not be supported in future versions of packages.
If you want to use a non exported function from your own library inside your own library, you can just use functionname() altough some package developers still prefer packagename:::functionname().
I'm creating an R package that will use a single function from plyr. According to this roxygen2 vignette:
If you are using just a few functions from another package, the
recommended option is to note the package name in the Imports: field
of the DESCRIPTION file and call the function(s) explicitly using ::,
e.g., pkg::fun().
That sounds good. I'm using plyr::ldply() - the full call with :: - so I list plyr in Imports: in my DESCRIPTION file. However, when I use devtools::check() I get this:
* checking dependencies in R code ... NOTE
All declared Imports should be used:
‘plyr’
All declared Imports should be used.
Why do I get this note?
I am able to avoid the note by adding #importFrom dplyr ldply in the file that is using plyr, but then I end but having ldply in my package namespace. Which I do not want, and should not need as I am using plyr::ldply() the single time I use the function.
Any pointers would be appreciated!
(This question might be relevant.)
If ldply() is important for your package's functionality, then you do want it in your package namespace. That is the point of namespace imports. Functions that you need, should be in the package namespace because this is where R will look first for the definition of functions, before then traversing the base namespace and the attached packages. It means that no matter what other packages are loaded or unloaded, attached or unattached, your package will always have access to that function. In such cases, use:
#importFrom plyr ldply
And you can just refer to ldply() without the plyr:: prefix just as if it were another function in your package.
If ldply() is not so important - perhaps it is called only once in a not commonly used function - then, Writing R Extensions 1.5.1 gives the following advice:
If a package only needs a few objects from another package it can use a fully qualified variable reference in the code instead of a formal import. A fully qualified reference to the function f in package foo is of the form foo::f. This is slightly less efficient than a formal import and also loses the advantage of recording all dependencies in the NAMESPACE file (but they still need to be recorded in the DESCRIPTION file). Evaluating foo::f will cause package foo to be loaded, but not attached, if it was not loaded already—this can be an advantage in delaying the loading of a rarely used package.
(I think this advice is actually a little outdated because it is implying more separation between DESCRIPTION and NAMESPACE than currently exists.) It implies you should use #import plyr and refer to the function as plyr::ldply(). But in reality, it's actually suggesting something like putting plyr in the Suggests field of DESCRIPTION, which isn't exactly accommodated by roxygen2 markup nor exactly compliant with R CMD check.
In sum, the official line is that Hadley's advice (which you are quoting) is only preferred for rarely used functions from rarely used packages (and/or packages that take a considerable amount of time to load). Otherwise, just do #importFrom like WRE advises:
Using importFrom selectively rather than import is good practice and recommended notably when importing from packages with more than a dozen exports.
I'm working on an R package at present and trying to follow the best practice guidelines provided by Hadley Wickham at http://r-pkgs.had.co.nz. As part of this, I'm aiming to have all of the package dependencies within the Imports section of the DESCRIPTION file rather than the Depends since I agree with the philosophy of not unnecessarily altering the global environment (something that many CRAN and Bioconductor packages don't seem to follow).
I want to use functions within the Bioconductor package rhdf5 within one of my package functions, in particular h5write(). The issue I've now run into is that it doesn't have its S3 methods declared as such in its NAMESPACE. They are declared using (e.g.)
export(h5write.default)
export(h5writeDataset.matrix)
rather than
S3method(h5write, default)
S3method(h5writeDataset, matrix)
The generic h5write is defined as:
h5write <- function(obj, file, name, ...) {
res <- UseMethod("h5write")
invisible(res)
}
In practice, this means that calls to rhdf5::h5write fail because there is no appropriate h5write method registered.
As far as I can see, there are three solutions to this:
Use Depends rather than Imports in the DESCRIPTION file.
Use library("rhdf5") or require("rhdf5") in the code for the relevant function.
Amend the NAMESPACE file for rhdf5 to use S3methods() rather than export().
All of these have disadvantages. Option 1 means that the package is loaded and attached to the global environment even if the relevant function in my package is never called. Option 2 means use of library in a package, which while again attaches the package to the global environment, and is also deprecated per Hadley Wickham's guidelines. Option 3 would mean relying on the other package author to update their package on Bioconductor and also means that the S3 methods are no longer exported which could in turn break other packages which rely on calling them explicitly.
Have I missed another alternative? I've looked elsewhere on StackOverflow and found the following somewhat relevant questions Importing S3 method from another package and
How to export S3 method so it is available in namespace? but nothing that directly addresses my issue. Of note, the key difference from the first of these two is that the generic and the method are both in the same package, but the issue is the use of export rather than S3method.
Sample code to reproduce the error (without needing to create a package):
loadNamespace("rhdf5")
rdhf5::h5write(1:4, "test.h5", "test")
Error in UseMethod("h5write") :
no applicable method for 'h5write' applied to an object of class
"c('integer', 'numeric')
Alternatively, there is a skeleton package at https://github.com/NikNakk/s3issuedemo which provides a single function demonstrateIssue() which reproduces the error message. It can be installed using devtools::install_github("NikNakk/s3issuedemo").
The key here is to import the specific methods in addition to the generic you want to use. Here is how you can get it to work for the default method.
Note: this assumes that the test.h5 file already exists.
#' #importFrom rhdf5 h5write.default
#' #importFrom rhdf5 h5write
#' #export
myFun <- function(){
h5write(1:4, "test.h5", "test")
}
I also have put up my own small package demonstrating this here.
This question is related to Rcmd check in R-Devel (3.1.0).
I am maintaining a package, call it A, that "Depends" on another package, let me call this second package B. I have used "Depends" instead of "import" for the following reasons:
most people using package A also use package B.
package A extensively use function from package B.
package B, itself, "depends" on other packages.
Package A make use of "unexported" function of package B and Rcmd check complaints about the following: Unexported objects imported by ':::' calls (as a NOTE, but I want to remove all of them). My question is: how should I properly handle this note? How should I properly make use of "unexported" function from another package?
I know that we should not use "unexported" function, but I am involved in the development of both packages.