5

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.

2 Answers 2

8

Here a solution using deparse:

> grep ("sort", deparse(shapiro.test))
[1] 5
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

Both answers are similar and excellent. I gave the 'correct' to the other answer just seemed slightly neater. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.