Repository navigation
[TOC]
R is an open source programming language that was developed for statistics and data analysis. It's easiest to use R through RStudio, which is an integrated development environment. RStudio offers lots of tools to make your life easier, so it's certainly worth using!
There are many great tutorials on using R and this wiki isn't aiming to better them, but to bring some of the information to the same place. For further learning consider the following resources:
- R for Data Science book by Wickham and Grolemund
- Efficient R programming book by Gillespie and Lovelace
- R Markdown: The Definitive Guide book by Xie, Allaire, and Grolemund
- Geocomputation with R book by Lovelace, Nowosad and Muenchow
- Text Mining with R book by Silge and Robinson
- R packages book by Wickham
- Advanced R book by Wickham
- Building reproducible analytical pipelines with R by Bruno Rodriques
- R programming MOOC by Johns Hopkins University
- Intro to R programming course by CCACE at University of Edinburgh.
- R-bloggers collects blogs written about R from around the world
- Maps in R
- Working with labelled survey data (e.g. SPSS) in R.
- Captions and citations in Rmarkdown.
- Agile data science.
- GovDown templates - could be adapted!.
- Sending dashboard emails
- First package in an hour
- Shiny tutorial
- Using parquet files can hugely speed up your code
- Documenting functions
- Assertive programming to catch data errors early
If you have questions Stack Overflow probably has an answer already, and the #rstats handle on Twitter is well used.
R uses packages to extend functionality, think of these like little toolboxes of ready made scripts. Amazingly, there are 10,000 of these available! I prefer to keep things simple and use as few as possible, but to help you choose which you might need there is a page which collects together packages for different tasks.
If you're new to programming, start simple. Think about breaking the task into sections: reading your data, transforming your data (if required), and then plotting some variables. This simple approach will help you build knowledge to do more complex things.
Hadley Wickham and associates have done some great work on lowering the bar to data analysis in R. He's grouped many of his packages together into the Tidyverse. You can read more about these on the dedicated website. To install the tidyverse, run the following command in your R(Studio) console:
install.packages("tidyverse")To get help using R type ?function_name in your console, or use the help pane in RStudio.
This will pull up the help page for that particular function, which includes sections on what arguments a function takes, what the defaults are and some example uses.
The tidyverse website is invaluable for working with tidyverse packages.
There are many ways to read data into R. Some useful packages are:
- arrow for parquet, but excellent with csv too
- readr for csv type files
- readxl for Excel files
- haven for Stata and SPSS files
Only readr is part of the core tidyverse, so if you need the others you'll need to install them with:
install.packages("arrow")
install.packages("readxl")
install.packages("haven")How do you read data in practice?
When you run a read command in R it looks at the file you've pointed it to and extracts the information.
If you have not told R to assign (put) this information to a variable it will print it to your console.
For example, if you're reading a file called test.csv using the readr package, here's how you'd go about it (note anything after a # is a comment and is not run by R):
# Load the readr package
library(readr)
# print the file to the console
read_csv("test.csv")
# assign the file to x
x <- read_csv("test.csv")In the RStudio environment pane you'll now have a new variable called x, along with a little information about it. The same method applies to the other packages/functions mentioned in this section for reading data into R. Note that R loads data into your RAM, so the size of file you can open is limited by how much RAM you have. A 2 MB file takes up approximately 4 MB of RAM when loaded into R.
This RAM use is one of the big advantages of using arrow, which uses Apache Hive.
Arrow can work on file(s) without loading them into R!
It's even compatible with dplyr verbs.
There's a comprehensive R cookbook for Arrow, but here's a quick example:
f = list.files(".", pattern = "csv")
open_dataset(f, format = "csv") %>%
filter(col_x == "bananas") %>%
count(something) %>%
collect()Often when we've read data into R it isn't ready for analysis, but needs manipulating. There are a thousand and one ways to do this in R and learning them is time spent far better than copy/pasting in a spreadsheet.
The tidyr package is really useful for converting between wide and long format. See the gather and spread functions for examples.
dplyr mainly offers up database like functionality. This means you can do operations on subsets of your data. At its most simple this is like a pivot table in a spreadsheet. There are so many tricks here it's worth exploring the web link to see what's possible.
Another package to look at is stringr, which helps you work with character data.
There are three main plotting packages in R, these are base (what comes with R as standard), lattice and ggplot2. I'm not going to cover lattice as it's complicated and the times one needs it are limited. Plotting in base R is great and can give lots of control and some very quick plots. In contrast, ggplot2 lets you do complex graphics quite easily. In order to use ggplot2, you'll need your data in a tidy format, which is what the previous section on transforming data is for!
- tidymodels framework
- Guide to anova on twitter
- R Markdown blends a mix of markdown with code to create outputs in a range of formats, e.g. html, pdf, Word
- Quarto is a newer implementation of R Markdown which works better with languages other than R, e.g. Python
- Flexdashboard is a package that uses R Markdown to create dashboards, these can be static html or interactive Shiny ones
- Shiny
- A number of packages exist to send html emails from R, these can include data viz and can combat dashboard fatigue (e.g. a weekly status update on a service). One package to do this is Blastula.
It's possible to create many types of outputs from R. For pdfs, Word, images, etc. there are established practices for how we share these. But for dashboards (either static or interactive), these can require further infrastructure.
Static R Markdown and Quarto html outputs can be hosted on any webserver (e.g. Github pages). These files are standalone webpages (leaflet maps do require a web connection), and so can also be emailed. html with interactivity (i.e. Shiny based) are discussed below.
R Markdown and Quarto can output in Github flavoured markdown, which renders nicely in Github's markdown interpreter.
This is activated with output: github_document in R Markdown and format: gfm in Quarto.
You can use this to create README files, or just host internal analysis content.
R is able to be run as a server and provide on-the-fly calculation for dashboards; this is typically achieved with the Shiny package. Shiny requires more infrastructure than a static html because of the R/Shiny server for the interactivity, hence you cannot use Github pages or other plain web servers. RStudio (the maintainer for Shiny) provide a hosting service on shinyapps.io, which has a number of price tiers including free. Use for shinyapps.io is capped on running hours users and authentication.
Shiny Server is an open source stack which can be deployed, but this doesn't include user authentication. RStudio provide a paid version of Shiny Server which adds user authentication and other features.
ShinyProxy is a fully featured, open source host for Shiny apps. This includes user authentication. ShinyProxy takes apps packaged in Docker containers, which makes them portable for other use cases. Some guides for getting started with ShinyProxy:
- DigitalOcean marketplace app
- How to Dockerise Shiny apps
- Rocker project
- Deploying apps to ShinyProxy
- ShinyProxy on AWS
- Towards data science: ShinyProxy
- Deploy Shiny with GH actions
