Question

How to find the file that contains the code of an R function?

I have R 4.3.2 installed on my Windows PC. I downloaded it from https://cran.r-project.org/bin/windows/base/. I have not downloaded the .tar.gz file with the R source code.

I know how to view the code of a function. If I type chisq.test in the console, for example, I get the code for the chisq.test function. This is a base function from the package stats.

The thing is: that code shown in the console must be stored somewhere, in some file on my computer. The code could not be displayed if it were not so.

Where is it? Is it a general method to find such locations?

I really tried to find it with no results. It's nowhere in C:/Program Files/R/R-4.3.2. I uploaded it to a GitHub repository and searched chisq.test and got no results either. I also looked in other folders in the same hard drive and found nothing. I didn't find anything useful on stackoverflow either.

I expect the code to be stored somewhere.

 3  77  3
1 Jan 1970

Solution

 3

As mentioned by @StephaneLaurent in comments, a standard installation of R doesn't include the source code in a human-readable text format; it's instead in a binary format that is more convenient for R to unpack.

From the console/terminal window, R RHOME will give you R's home directory (provided R is in your path so that it can be found ...) Starting from this directory, changing to library\stats\R will show you where the code actually lives. Unfortunately, the package code is stored as two binary files, stats.rdb and stats.rdx. This question asks how to open .rdb files (not trivial). These files are more thoroughly described in the section on "Lazy loading" in the R internals manual. (This article by Brian Ripley explains what "lazy loading" is, why it is useful, and how R uses the rdb/rdx machinery.)

It would be more practical to either download and unpack the R source code from CRAN (and navigate to src/library/stats/R/chisq.test.R), or to look at the corresponding file on the r-svn Github mirror (or on the official R Subversion server).

2024-07-24
Ben Bolker

Solution

 1

You can execute the function .libPaths() to get the file paths where your packages are installed. One of those folders is for user-installed packages, and other is for base packages, like {stats}. This answer is based on this StackOverflow answer.

Another option is the R.home() function, which will return the path of your R installation. In that folder, the library directory contains base packages, such as {stats}.

The {lookup} package also allows you to browse function definitions, including compiled code, S3 and S4 methods:

# install.packages("devtools")
# devtools::install_github("jimhester/lookup")

library(lookup)

lookup(chisq.test)

lookup::lookup_usage("chisq.test")

You can also browse R's source code in the GitHub mirror

2024-07-23
Bastián Olea Herrera