Reputation: 191
I'm writing a function that uses some lubridate
functions.
However, I'm not sure how to import the function %within%
from lubridate. Usually this is easy, as I just use lubridate::function. When I tried this with the %within% operator, this did not work. Is there any way to use operators from packages without loading the entire package itself?
Upvotes: 3
Views: 909
Reputation: 1751
Yes. The issue here is that %within%
is a special symbol that is also a function. In R, pretty much everything is a function. For example, when you do 2 + 2
, R actually interprets that as
`+`(2, 2)
Check this section from "Advanced R" by Hadley Wickham to understand this details.
So the most direct answer to your question would be: use the same logic for the %within%
function, but escaping the %
symbol and directly specifying arguments a and b for the function.
lubridate::`%within%`(a, b)
If you're developing a package yourself, you can document your function that uses %within%
using roxygen2
. All you need to do is:
#' @title Your Nice Function
#' @description This is a description...
#' @param a Your first param
#' @param b Your second param
#' @importFrom lubridate \%within\%
your_nice_function <- function(a, b) {
...
}
That does it, because you're saying that this function imports the specific function %within%
from lubridate, without loading the entire lubridate package.
However, if you just want to use the function inside a script the most "familiar" way possible, maybe the best way is to:
`%within%` <- lubridate::`%within%`
By doing so, you're essentially copying the function to a local variable of the same name.
Upvotes: 8