How To Find Out What An R Function’s Code Is

As a data scientist and R enthusiast, I often come across situations where I need to understand the inner workings of an R function. Whether it’s to troubleshoot a bug, improve performance, or simply satisfy my curiosity, being able to dig into the code of an R function is an invaluable skill. In this article, I’ll share my personal insights and techniques on how to uncover the code behind an R function.

Using the “body” Function

One of the simplest methods to find out what an R function’s code is, is by using the body function. This function allows you to access the body of a function directly, revealing its underlying code. Let’s take a simple example of the mean function to illustrate this.


body(mean)

By executing the body(mean) command, you can see the actual code that powers the mean function. This straightforward approach is handy for quick inspections of small and predefined functions.

Using the “edit” Function

When I need to dive deeper into a function, I often turn to the edit function. This nifty tool opens up the source code of a function in the default text editor, allowing for a more comprehensive examination. For example, if I want to explore the code behind the lm function, I would use:


edit(lm)

Using edit(lm) launches a text editor with the complete source code of the lm function, enabling in-depth analysis and understanding of the underlying implementation.

Using the “getAnywhere” Function

In cases where I need to locate the definition of a function that isn’t in the current environment, the getAnywhere function comes to the rescue. This function searches all loaded namespaces to find the specified function and retrieve its source code. For instance, to find the code for the filter function from the dplyr package, I would use:


getAnywhere(filter)

Calling getAnywhere(filter) would display the source code of the filter function, regardless of its location, making it a powerful tool for exploring functions from external packages.

Conclusion

Being able to uncover the code behind an R function is not just a valuable skill, but also a gateway to deeper understanding and mastery of the language. Whether it’s through the body, edit, or getAnywhere function, having the ability to peek into the inner workings of R functions allows for greater insight and proficiency. So, next time you find yourself curious about how a particular R function operates, don’t hesitate to dive into its code!