JMM’s notes on

R

The R Project for Statistics

R is free software for basically doing statistics. I learned it originally back in Berkeley as a stats major, and I originally hated it because I was also a CS major and was not used to array languages. Now I really like it.

It’s a GNU project, so it’s free software that anyone can use, study, and improve. And it’s also basically the programming language used for statistics in Berkeley (at least when I was there back in 2013). I’m pretty thankful I didn’t have to deal with proprietary software to study stats; the same can’t be said for neuroscience, where most people still use MATLAB.

Cheat sheet

Sometimes I don’t use R for a while and I forget even the most basic things.

system2
Run a command
original_dir <- getwd()
Get current directory
setwd(target_dir)
Change directory

Save a plot

If you don’t want to plot it to a window:

png(filename = "whatever.png")
plot(rnorm(100), rnorm(100))
dev.off()

If you already have a window:

dev.print(png, "whatever.png", width = 480)

See this documentation for dev.print and this page about png (or this page for a list of graphical devices).

JSON

See https://cran.r-project.org/web/packages/jsonlite/vignettes/json-aaquickstart.html.

library(jsonlite)
all.equal(mtcars, fromJSON(toJSON(mtcars)))

See also help for the functions read_json, parse_json, and write_json.

Nix

I use Nix with R for reproducibility and to parallelize analyses (i.e. run analyses on computers much more powerful than my decade-old laptop). My Stan page has a Nix setup (also see direnv notes).

Most packages are under the “rPackages” attribute. Many packages will automatically include required dependencies (though I’ve patched some that were missing). One issue though with Stan is that it needs a compiler at run time, so you’ll need to include that in your environment.

Emacs Speaks Statistics

I’ve apparently forgotten that to turn a shell already running R into an inferior-ess-mode buffer you use M-x ess-remote. For example, for running R from a Nix shell, I might use something like M-x shell, nix-shell . -A blah-test, R, M-x ess-remote.

Recent changes to check out

Base R has some new functionality I probably need to learn