I'm trying to test whether a particular variable or function exists in a package. For example, suppose I wanted to test whether a function called plot
existed in package 'graphics'.
The following tests whether a function plot
exists, but not what package it comes from:
exists('plot', mode='function')
Or I can test that something called plot
exists in the graphics
package, but this doesn't tell me whether it's a function:
'plot' %in% ls('package:graphics')
Is there a nice way to ask "does an object called X exist in package Y of mode Z"? (Essentially, can I restrict exists
to a particular package?)
(Yes, I can combine the above two lines to first test that plot
is in graphics
and then ask for the mode of plot
, but what if I had my own function plot
masking graphics::plot
? Could I then trust the output of exists('plot', mode='function')
? )
Background: writing tests for a package of mine and want to test that various functions are exported. I'm using package testthat
which executes tests in an environment where I can see all the internal functions of the package, and have been stung by exists('myfunction', mode='function')
returning true, but I've actually forgotten to export myfunction
. I want to test that various functions are exported.
One way to check if a function is defined is to test it with an if statement. The trick is to test the function as a method of the window object. The code in the brackets will execute if the function is defined.
Check if an Object of the Specified Name is Defined or not in R Programming – exists() Function. exists() function in R Programming Language is used to check if an object with the names specified in the argument of the function is defined or not. It returns TRUE if the object is found.
Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
You should just use hasattr(some_class, "some_function") for more clarity and because sometimes dict is not used, although this still does not check whether you're dealing with a function or not.
Oh, I found it.
I noticed that in ?ls
it says that the first argument ('package:graphics'
for me) also counts as an environment. exists
' where
argument has the same documentation as ls
' name
argument, so I guessed 'package:graphics'
might work there too:
exists('plot', where='package:graphics', mode='function')
[1] TRUE # huzzah!
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