timcdlucas
timcdlucas

Reputation: 1364

Searching a functions source code

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.

Upvotes: 5

Views: 513

Answers (2)

user1981275
user1981275

Reputation: 13372

Here a solution using deparse:

> grep ("sort", deparse(shapiro.test))
[1] 5

Upvotes: 8

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

You could wrap the function in capture.output, which will convert each line to an element in a character vector.

> grep("sort",capture.output(shapiro.test))
[1] 5 

Or you could just call edit(shapiro.test) and use the text editor specified by options(editor=) to search through the function.

Upvotes: 3

Related Questions