rpackageexists

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


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

Solution

  • You can use the exists function to look inside namespaces:

    exists2 <- function(x) {
    
        assertthat::assert_that(assertthat::is.string(x))
    
        split <- base::strsplit(x, "::")[[1]]
    
        if (length(split) == 1) {
            base::exists(split[1])
        } else if (length(split) == 2) {
            base::exists(split[2], envir = base::asNamespace(split[1]))
        } else {
            stop(paste0("exists2 cannot handle ", x))
        }
    }