In R, you can view the source of a function as a function is simply another object.
I am looking for a way to search through this source code, without knowing the file that the source is saved in.
For example, I might want to know if the function shapiro.test
contains the function sort
(it does).
If shapiro.test
was a string or a vector of strings I would use
grep('sort', shapiro.test)
But as shapiro.test
is a function, this gives the error "Error in as.character(x) :
cannot coerce type 'closure' to vector of type 'character'".
I've had no luck trying to coerce the function to a string. Just as an extra, I'm not expecting to be able to search through base functions as they are compiled.
Practical Data Science using Python We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.
If you want to view the code built-in to the R interpreter, you will need to download/unpack the R sources; or you can view the sources online via the R Subversion repository or Winston Chang's github mirror.
source causes R to accept its input from the named file or URL or connection or expressions directly.
In simple we can say source code is a set of instructions/commands and statements which is written by a programmer by using a computer programming language like C, C++, Java, Python, Assembly language etc. So statements written in any programming language is termed as source code.
Here a solution using deparse
:
> grep ("sort", deparse(shapiro.test))
[1] 5
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