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):
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 likelm
<primitive>
or<bytecode>
. - Use the fully qualified namespace:
This ensures you’re looking at the function in thestats::lm
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:
This opens the function’s source in the RStudio Viewer pane, if available.View(lm)
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
- If you’re looking to master common coding challenges, try Grokking the Coding Interview: Patterns for Coding Questions.
- For more advanced data structure and algorithm discussions, see Grokking Data Structures & Algorithms for Coding Interviews.
- Interested in designing scalable systems or microservices? Grokking System Design Fundamentals is a great place to begin.
Mock Interviews and Video Tutorials
- Get one-on-one guidance from ex-FAANG engineers with a Coding Mock Interview or System Design Mock Interview.
- Check out the DesignGurus.io YouTube channel for more technical tutorials and interview tips.