• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
  • Created about 9 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

How to get at R source. I am sick of Googling this. I am writing it down this time.

Accessing R Source

2017-07-31 update: Since I wrote this @jimhester has created the lookup package to automate this process. So if all you want is the result, just use that! If you want a bit more context, then keep reading. AFAIK this info is still fundamentally sound.

How to get at R source. I am sick of Googling this. I am writing it down this time.

TL;DR

methods(<S3_GENERIC>)
<S3_GENERIC>.default
<S3_GENERIC>.<CLASS>
getAnywhere(<S3_GENERIC>.<CLASS>)
getS3method("<S3_GENERIC>", "<CLASS>")
<NAMESPACE>:::<S3_GENERIC>.<CLASS>

References

The definitive reference is this classic R News article:

Accessing the Sources

Uwe Ligges

https://cran.r-project.org/doc/Rnews/Rnews_2006-4.pdf

Volume 6/4, October 2006. Go to page 43.

Another good reference is the help file for method():

https://stat.ethz.ch/R-manual/R-patched/library/utils/html/methods.html

Just print it

If you are lucky, just printing the function will work.

setNames
#> function (object = nm, nm) 
#> {
#>     names(object) <- nm
#>     object
#> }
#> <bytecode: 0x7fce93c98920>
#> <environment: namespace:stats>

But there are many ways this can fail.

vector             # .Internal
#> function (mode = "logical", length = 0L) 
#> .Internal(vector(mode, length))
#> <bytecode: 0x7fce94835c40>
#> <environment: namespace:base>
class              # .Primitive
#> function (x)  .Primitive("class")
subset             # S3 generic
#> function (x, ...) 
#> UseMethod("subset")
#> <bytecode: 0x7fce933c0178>
#> <environment: namespace:base>

What then?

Function is an S3 generic

These are characterized by UseMethod() in the printed result:

subset
#> function (x, ...) 
#> UseMethod("subset")
#> <bytecode: 0x7fce933c0178>
#> <environment: namespace:base>

Print the default method by appending .default:

subset.default
#> function (x, subset, ...) 
#> {
#>     if (!is.logical(subset)) 
#>         stop("'subset' must be logical")
#>     x[subset & !is.na(subset)]
#> }
#> <bytecode: 0x7fce935f1228>
#> <environment: namespace:base>

Or list the methods for this generic:

methods(subset)
#> [1] subset.data.frame subset.default    subset.matrix    
#> see '?methods' for accessing help and source code

Then print the method you seek:

subset.matrix
#> function (x, subset, select, drop = FALSE, ...) 
#> {
#>     if (missing(select)) 
#>         vars <- TRUE
#>     else {
#>         nl <- as.list(1L:ncol(x))
#>         names(nl) <- colnames(x)
#>         vars <- eval(substitute(select), nl, parent.frame())
#>     }
#>     if (missing(subset)) 
#>         subset <- TRUE
#>     else if (!is.logical(subset)) 
#>         stop("'subset' must be logical")
#>     x[subset & !is.na(subset), vars, drop = drop]
#> }
#> <bytecode: 0x7fce93314388>
#> <environment: namespace:base>

Sometimes the method definition is not exported from the package namespace. That's indicated by an asterisk * in the listing (pardon the way I do this, but I have to send through capture.output() if the asterisks are to survive tail():

mout <- capture.output(methods(print))
tail(mout)
#> [1] "[195] print.vignette*                                   "
#> [2] "[196] print.warnings                                    "
#> [3] "[197] print.xgettext*                                   "
#> [4] "[198] print.xngettext*                                  "
#> [5] "[199] print.xtabs*                                      "
#> [6] "see '?methods' for accessing help and source code"

Good news: you've found the function you need. Bad news: you still can't read the source.

print.xgettext
#> Error in eval(expr, envir, enclos): object 'print.xgettext' not found

Use getAnywhere() or getS3method() to close the deal:

getAnywhere(print.xgettext)
#> A single object matching 'print.xgettext' was found
#> It was found in the following places
#>   registered S3 method for print from namespace tools
#>   namespace:tools
#> with value
#> 
#> function (x, ...) 
#> {
#>     cat(x, sep = "\n")
#>     invisible(x)
#> }
#> <bytecode: 0x7fce9787e150>
#> <environment: namespace:tools>

This printed the source AND we learned the associated namespace. If you know the namespace, you can also use ::: to see source:

tools:::print.xgettext
#> function (x, ...) 
#> {
#>     cat(x, sep = "\n")
#>     invisible(x)
#> }
#> <bytecode: 0x7fce9787e150>
#> <environment: namespace:tools>

Compiled code

Whenever you see .C(), .Call(), .Fortran(), .External(), or .Internal() and .Primitive(), the source you seek is in underlying compiled code.

You need to locate the source code of R or the associated add-on package on the internet or download it locally. Then browse around or search.

Visit the source of R on the internet:

Download source of R itself:

  • Download source for current release from https://cran.r-project.org, e.g. R-3.2.2.tar.gz, and unpack it.

    tar xvf R-3.2.2.tar.gz
    
  • See more info there about getting the development version.

  • Or checkout from the official Subversion repository https://svn.r-project.org/R/.

How to find what you need in the R source (paraphrasing Ligges, in places):

  • For R and standard R packages, look in subdirs of $R_HOME/src/, most especially $R_HOME/src/main/.
  • If calling R function is .Primitive() or .Internal(), find the entry point $R HOME/src/main/names.c. Then try to find that function. Example below.
  • Use the GitHub search capabilities.

Example: I want the source for levels<-.

`levels<-`    # .Primitive()
#> function (x, value)  .Primitive("levels<-")

Search for levels<- in $R HOME/src/main/names.c and we find this line:

{"levels<-", do_levelsgets, 0, 1, 2, {PP_FUNCALL, PREC_LEFT, 1}}

which tells us we're looking for do_levelsgets. Now use your search capability (GitHub? grep?) to look for that within the files below $R_HOME/src/. I choose the GitHub option and use this query:

 do_levelsgets path:src/main

And finally arrive at my destination: lines 1242 through 1261 in $R_HOME/src/main/attrib.c.

Visit the source of an R package on the internet:

  • If developed on GitHub, go to package's official repo. Ideally, this will be provided as a URL on the package's CRAN page, but sadly not always the case.
  • If the package is on CRAN but not on GitHub, go to the read-only mirror of its source from the METACRAN project.

Download source of an add-on package:

How to find what you need in R package source:

  • Look in the src directory. If you are lucky, there will be a file that obviously contains the function of interest.
  • Otherwise, search with grep, your editor/IDE, or GitHub queries and follow the trail to rainbow's end.

Example: I want the source for dplyr::bind_rows. dplyr is developed on GitHub.

First I search within the R directory with this GitHub search query:

bind_rows path:R

GitHub search only shows you the first one or two matches within a file, but I gather that R/bind.r is where I want to look. I visit it in the browser and use the browser to search for bind_rows, which reveals the function definition. That reveals I actually need bind_rows_.

So I do another GitHub search with this query:

bind_rows_

which reveals hits in

R/bind.r
R/RcppExports.R
src/bind.cpp
src/RcppExports.cpp

Reading the relevant bit of src/bind.cpp reveals I really need rbind__impl.

So I do another GitHub search with this query:

rbind__impl

And finally arrive at my destination: lines 7 though 119 of src/bind.cpp.

Things I haven't covered

An incomplete list:

  • S4
  • Other places to put code, e.g. R-Forge or BitBucket

More Repositories

1

googlesheets

Google Spreadsheets R API
R
786
star
2

happy-git-with-r

Using Git and GitHub with R, Rstudio, and R Markdown
TeX
550
star
3

row-oriented-workflows

Row-oriented workflows in R with the tidyverse
R
406
star
4

here_here

I love the here package. Here's why.
289
star
5

gapminder

Excerpt from the Gapminder data, as an R data package and in plain text delimited form
R
273
star
6

ggplot2-tutorial

Teaching materials for the R package ggplot2
R
236
star
7

code-smells-and-feels

Talk on code smells and feels and how to change that via refactoring
R
230
star
8

send-email-with-r

How to send a bunch of email from R
R
205
star
9

r-graph-catalog

All graphs in โ€œCreating More Effective Graphsโ€, made with R package ggplot2.
R
187
star
10

repurrrsive

Recursive lists to use in teaching and examples, because there is no mtcars for lists.
R
133
star
11

free-photos

Places to find CC0 photos and the like
116
star
12

debugging

Talk about general debugging strategies. How to be less confused and frustrated.
R
112
star
13

purrr-tutorial

Materials for getting to the know the R package purrr
HTML
111
star
14

pkg-dev-tutorial

Package Development tutorial for useR! 2019 Toulouse
R
89
star
15

docker-why

Notes about why an R user would use Docker
57
star
16

scary-excel-stories

Sobering things about Excel
55
star
17

jadd

RStudio addins
R
52
star
18

bingo

Generate Bingo cards with R.
R
48
star
19

sanesheets

A rant about spreadsheets.
47
star
20

githug

Interface to local and remote Git operations
R
47
star
21

how-to-name-files

R
43
star
22

manipulate-xml-with-purrr-dplyr-tidyr

Example of taming XML with nested data frames and purrr
HTML
40
star
23

lego-rstats

Photos that depict R data structures and operations via Lego
R
39
star
24

analyze-github-stuff-with-r

Marshal data from the GitHub API with R
R
38
star
25

2015-06-28_r-summit-talk

Talk at R Summit and Workshop about using R Markdown and GitHub in your workflow
38
star
26

operation-chromebook

Setup notes for the Bryan family Chromebooks
35
star
27

zen-art-workflow

Links and credits for a talk: Zen And The aRt Of Workflow Maintenance
R
35
star
28

2015-02-23_bryan-fields-talk

Talk at Workshop on Visualization for Big Data: Strategies and Principles, Fields Institute http://www.fields.utoronto.ca/programs/scientific/14-15/bigdata/visualization/
33
star
29

2016-06_spreadsheets

Talks given in May and June 2016.
32
star
30

2019-07_useR-toulouse-usethis

Talk about the usethis R package at useR! 2019 Toulouse
R
30
star
31

foofactors

Make Factors Less Aggravating
R
29
star
32

excelgesis

Critical explanation or interpretation of ... Excel spreadsheets
R
26
star
33

lotr

R
26
star
34

2024_raukr-purrr-pkg-dev

Jenny Bryan's instruction at RaukR: Advanced R for Bioinformatics Summer School
R
23
star
35

lotr-tidy

Tidy data lesson using Lord of the Rings data.
23
star
36

regexcite

PACKAGE EXISTS FOR DEMONSTRATION PURPOSES ONLY! Make Regular Expressions More Exciting
R
21
star
37

STAT545A_2013

UBC grad course in data analysis with R
HTML
21
star
38

earl-london-2017-bryan

Jenny Bryan talk at EARL London, 2017 September 12/13/14
21
star
39

2018-09_purrr-latinr

R
20
star
40

scream

Get replies and quotes of a tweet
19
star
41

jeremy-howard-posit-conf-2023

Notebook seen in Jeremy Howard's keynote at posit::conf(2023)
Jupyter Notebook
19
star
42

tidy-eval-context

17
star
43

2015-08_bryan-jsm-stat-data-sci-talk

Bryan talk at JSM 2015 re: are statisticians data scientists
R
17
star
44

stat540_2014

STAT540 Statistical Methods for High Dimensional Biology, January - April 2014
R
16
star
45

happy-git-and-github-for-the-user

Talk: Happy Git and GitHub for the useR
14
star
46

frogs

Data from the Calaveras Jumping Frog Jubilee
R
11
star
47

organization-and-naming

Draft of mini-lectures about file organization and naming.
9
star
48

2018_advent-of-code

R
8
star
49

candy

candy survey data
R
8
star
50

2024-04_netherlands-escience

8
star
51

2014-05-12-ubc

Python
8
star
52

making-messages

7
star
53

yelpr

Call the Yelp API from R ... at this point, just helping a student!
R
6
star
54

bioinformatics.ca-swc-r

Software Carpentry Bootcamp for bioinformatics.ca 2014-05-12
R
6
star
55

appveyorWTF

WTF AppVeyor, WTF?
R
5
star
56

2017_advent-of-code

R
5
star
57

STAT545

UBC grad course in data analysis with R
5
star
58

user2016-git-tutorial

Tutorial for useR! 2016 @ Stanford
4
star
59

jennybryan.org

Personal website of Jenny Bryan
HTML
4
star
60

swcR_duke

R content from Duke Software Carpentry Workshop May 2013.
R
4
star
61

jblibminer

Explore Your R Libraries
R
4
star
62

test-drive-a-package

try an experimental version of an R package without messing with your main R library
3
star
63

babystats

Bit of data on the Bryan babies
R
3
star
64

explore-libraries-seattle-practice

Just practicing!
R
3
star
65

miami-intermediate-r

Instructor repository for intermediate R room, U of Miami, Software Carpentry Boot Camp, January 2014
R
3
star
66

angrybunny

Split a single string
R
2
star
67

symlink-test

R
2
star
68

2021-06_raukr-iteration

R
2
star
69

furry-sniffle

A practice GitHub repo
2
star
70

teengecko

What the Package Does (One Line, Title Case)
R
2
star
71

xyztest

2
star
72

nfl

R
2
star
73

apple

Experimenting using GHA to render bookdown into gh-pages branch
TeX
2
star
74

localetest

What the Package Does (One Line, Title Case)
R
2
star
75

arms-length-render

Usage of rmarkdown::render() when intermediates and outputs don't live with source
R
2
star
76

vanNH

In-house statistics for the Vancouver Nighthawks of Major League Ultimate
HTML
2
star
77

testfun

Toy package with some tests
R
2
star
78

rmd-render-fun

R
2
star
79

cran-data-pkg-licenses

A look at the licenses used by data packages on CRAN
1
star
80

2013-11_sfu

Supporting documents for talk and workshop for SFU Statistics and Actuarial Science
1
star
81

README-as-visual-index

Autogenerate README to give visual index of a figure directory
R
1
star
82

refactor

Make Factors Less Annoying
R
1
star
83

vigilant-tribble

There's only one way to figure out how this works.
1
star
84

happy

I am happy
1
star
85

foofactors2

Happier Life With Factors
R
1
star
86

bellybutton

Data from "A Jungle in There" re: bacterial diversity in the adult human belly button
1
star
87

foofactors3

What the Package Does (One Line, Title Case)
R
1
star
88

2014-01-27-miami

Software Carpentry Bootcamp at the University of Miami
Python
1
star
89

stat545a-2013-hw06_baik-jon

Last homework for STAT545A
CSS
1
star
90

devhelp

What the Package Does (One Line, Title Case)
R
1
star
91

STAT545Assignment6

R
1
star
92

excuse-me-iris

Toy example used in the article "Excuse me, do you have a moment to talk about version control?"
R
1
star
93

googledrive-deployed-token-demo-service

R
1
star
94

fuzzy-peach

R
1
star
95

fluffybunny

What the Package Does (One Line, Title Case)
1
star
96

clouddeployoops

1
star
97

pudgy-pig

just testing some instructions
1
star
98

safecall

C
1
star
99

reimagined-goggles

Demo project created from raukR, OK to delete later
1
star
100

abcd

What the Package Does (One Line, Title Case)
R
1
star