Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how can I check for the existence of a function in an unloaded package?

Tags:

package

r

exists

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
like image 558
sdgfsdh Avatar asked Jul 28 '15 10:07

sdgfsdh


1 Answers

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
like image 134
Josh Avatar answered Sep 18 '22 00:09

Josh