I can check that a function exists in my environment:
> exists("is.zoo")
[1] FALSE
I can check that a function exists after loading a package by loading it:
> library(zoo)
> exists("is.zoo")
[1] TRUE
But how can I check that a function exists in a package without loading that package?
> exists("zoo::is.zoo")
[1] FALSE
You can view the source of a function even if its not loaded.
> exists("zoo::is.zoo")
[1] FALSE
> zoo::is.zoo
function (object)
inherits(object, "zoo")
<environment: namespace:zoo>
So you could exploit that with a function like this
exists_unloaded <- function(fn) {
tryCatch( {
fn
TRUE
}, error=function(e) FALSE
)
}
If the call to fn
errors, it'll return FALSE; if fn
shows the source, the TRUE
will be returned.
> exists("zoo::is.zoo")
[1] FALSE
> exists_unloaded(zoo::is.zoo)
[1] TRUE
> exists_unloaded(zoo::is.zootoo)
[1] FALSE
(Just be careful, as written exists_unloaded
returns TRUE
for all strings. Probably want to error if fn
is a string.)
edit:
Also, you can call a function without loading the package. I don't know your full use case, but it might obviate the need to check for its existence. (Of course, if the user hasn't installed the package, it will still fail.)
> exists("zoo::is.zoo")
[1] FALSE
> zoo::is.zoo(1)
> z <- zoo::as.zoo(1)
> zoo::is.zoo(z)
[1] TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With