If you're diving into R programming, there will come a time when you want to look under the hood and see how a function works. Maybe you're curious about the mechanics, or you want to understand it better to use it more effectively. Here's a guide to help you view the source code for a function in R.
Viewing the Source Code of a Function
Understanding the source code of a function can be immensely helpful for several reasons. It allows you to see the exact steps the function takes to produce its output, which can deepen your understanding of the R Programming Language.
1. Using the print or function Command
For functions that are not primitive (i.e., not written in C or Fortran), you can simply type the function name without parentheses, or use print.
R
# Example with the lm function
print(lm)
# or just
lm
Output:
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
2. Using the getAnywhere Function
The getAnywhere function can be used to locate and display the source code of a function, even if it is not exported from a namespace.
R
# Example with the lm function
getAnywhere(lm)
Output:
A single object matching ‘lm’ was found
It was found in the following places
package:stats
namespace:stats
with value
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
{
3. Using the View Function in RStudio
If you are using RStudio, you can use the View function to see the source code in a viewer.
R
# Example with the lm function
View(lm)
Output:
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts = NULL, offset, ...) {
4. Using the trace Function
For functions that are part of a package and might not be directly accessible, you can use the trace function to insert a tracing function that displays the source.
R
# Example with the lm function
trace(lm)
Output:
if (!qr)
z$qr <- NULL
z
}
<bytecode: 0x0000012c714000d0>
<environment: namespace:stats>
5. Using the deparse and body Functions
You can use deparse along with body to print the source code of a function.
R
# Example with the lm function
cat(deparse(body(lm)), sep = "\n")
Output:
{
ret.x <- x
ret.y <- y
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "weights", "na.action",
"offset"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
6. Viewing Source Code of S3 Methods
For S3 methods, you need to use the getS3method function to get the specific method for a class.
R
# Example with the plot function for lm objects
print(getS3method("plot", "lm"))
Output:
function (x, which = c(1, 2, 3, 5), caption = list("Residuals vs Fitted",
"Q-Q Residuals", "Scale-Location", "Cook's distance", "Residuals vs Leverage",
expression("Cook's dist vs Leverage* " * h[ii]/(1 - h[ii]))),
panel = if (add.smooth) function(x, y, ...) panel.smooth(x,
y, iter = iter.smooth, ...) else points, sub.caption = NULL,
main = "", ask = prod(par("mfcol")) < length(which) && dev.interactive(),
..., id.n = 3, labels.id = names(residuals(x)), cex.id = 0.75,
qqline = TRUE, cook.levels = c(0.5, 1), cook.col = 8, cook.lty = 2,
cook.legendChanges = list(), add.smooth = getOption("add.smooth"),
iter.smooth = if (isGlm) 0 else 3, label.pos = c(4, 2), cex.caption = 1,
cex.oma.main = 1.25, extend.ylim.f = 0.08)
{
7. Viewing Source Code of Functions from Packages
For functions that are part of a package, you can load the package and then use one of the above methods.
R
# Load the package
library(ggplot2)
# Example with the ggplot function
print(ggplot)
Output:
function (x, which = c(1, 2, 3, 5), caption = list("Residuals vs Fitted",
"Q-Q Residuals", "Scale-Location", "Cook's distance", "Residuals vs Leverage",
expression("Cook's dist vs Leverage* " * h[ii]/(1 - h[ii]))),
panel = if (add.smooth) function(x, y, ...) panel.smooth(x,
y, iter = iter.smooth, ...) else points, sub.caption = NULL,
main = "", ask = prod(par("mfcol")) < length(which) && dev.interactive(),
..., id.n = 3, labels.id = names(residuals(x)), cex.id = 0.75,
qqline = TRUE, cook.levels = c(0.5, 1), cook.col = 8, cook.lty = 2,
cook.legendChanges = list(), add.smooth = getOption("add.smooth"),
iter.smooth = if (isGlm) 0 else 3, label.pos = c(4, 2), cex.caption = 1,
cex.oma.main = 1.25, extend.ylim.f = 0.08)
{
Conclusion
Viewing the source code of functions in R is a valuable skill that can help you understand how functions work, debug issues, and even improve your programming skills. Whether you use basic commands like print or more advanced tools like debug, having the ability to look under the hood will make you a more effective R programmer.
Similar Reads
How to use the source Function in R In this article, we will be looking at the practical implementation of the source function in the R programming language. Source Function: Source function in R is used to use functions that are created in another R script. The syntax of this function is given below: source("Users/harsh/Desktop/Geeks
2 min read
How to Set a Breakpoint in Function Body in RStudio? When writing complex programs in R code, setting breakpoints can be a really useful tool in identifying and fixing issues. A breakpoint allows you to pause the execution of your code at a specific line, allowing you to inspect variables, step through your code, and understand its behavior. In this a
4 min read
How to plot user-defined functions in R? Plotting user-defined functions in R is a common task for visualizing mathematical functions, statistical models, or custom data transformations. This article provides a comprehensive guide on how to plot user-defined functions in R, including creating simple plots, enhancing them with additional fe
3 min read
How to Access the Script/Source History in RStudio? RStudio provides several tools for managing and revisiting your code where one of the great featured tool is the Script/Source History feature. This feature allows you to view and access previous commands and scripts, which can be particularly useful for tracking changes, debugging, or revisiting ea
5 min read
What Is The Data() Function In R? In this article, we will discuss what is data function and how it works in R Programming Language and also see all the available datasets in R. Data() Function In RIn R, the data() function is used to load datasets that come pre-installed with R packages or datasets that have been explicitly install
5 min read
How to Install an R Package from Source? There are several reasons why installing an R package from source may be required, including to get the most recent release, to use a particular patch, or to work with a package that only contains source files, and is not available in binary for a certain operating system. When it comes to installin
5 min read