Logo

How can I view the source code for a function in R?

In R, functions can be written in R (i.e., accessible as text) or compiled in native code (C, C++, or Fortran). If the function is purely an R function, you can often see its source directly; if it’s compiled, you will not see the R-level code because it doesn’t exist.

Simple Methods

  • Type the function’s name (without parentheses):
    lm
    
    You’ll see the R source code if it’s an R function. If it’s a primitive (compiled) function, you’ll get a short message like <primitive> or <bytecode>.
  • Use the fully qualified namespace:
    stats::lm
    
    This ensures you’re looking at the function in the stats package.
  • View S3 or S4 methods: Sometimes you need to check specific class methods:
    # For S3 methods
    getS3method("print", "lm") 
    
    # For S4 methods
    showMethods("anova")
    
  • Use View() in RStudio:
    View(lm)
    
    This opens the function’s source in the RStudio Viewer pane, if available.

What if the Function is Not Pure R?
If it’s a primitive or compiled function, R can’t show you its higher-level source code. Instead, you’ll see a <primitive> or similar note. In those cases, you’d have to look into the language R is calling (C, C++, Fortran, etc.) via the repository hosting R’s source code.

Why It Matters
Inspecting source code helps you understand how the function works, troubleshoot unexpected behavior, or extend functionalities. This is especially helpful if you’re debugging your own code or prepping for a coding interview that requires deep insights into R internals.

Further Skills and Interview Prep

Mock Interviews and Video Tutorials

CONTRIBUTOR
TechGrind