# Go to get latesdebian latest r sources.list
cat /etc/apt/sources.lisR essentials
Install R
Install R for the First Time
- download R
- for debian: Johannes Ranke. For Linux/Debian installation, crucial to update the source.list to include sources that have more recent versions of R. If not, will get very old R versions that is not compatible with many packages.
- add R to path for Windows. In Windows Path, add for example: C:/Program Files/R/R-3.6.2/bin/x64/ and C:/Rtools/bin
- Install Rtools for building R packages.
- download R-studio
- Open R-studio and auto-detect R
- Install additional packages
Linux R Install
For linux/Debian, to Install latest R:
R essentials
Required material
- Read The Kitchen Counter Observatory, [@kieranskitchen]
- Discussion of what data hides and reveals.
- Read R for Data Science, Chapter 4 “Data transformation”, [@r4ds]
- Provides an overview of manipulating datasets using
dplyr.
- Provides an overview of manipulating datasets using
- Read Data Feminism, Chapter 6 “The Numbers Don’t Speak for Themselves”, [@datafeminism2020]
- Discusses the need to consider data within the broader context that generated them.
- Read R Generation, [@Thieme2018]
- Provides background information about R.
Key concepts and skills
- Understanding foundational aspects of R and RStudio enables a gradual improvement of workflows. For instance, being able to use key
dplyrverbs and make graphs withggplot2makes manipulating and understanding datasets easier. - But there is an awful lot of functionality in the
tidyverseincluding importing data, dataset manipulation, string manipulation, and factors. You do not need to know it all at once, but it is important to know that you do not yet know it. - Beyond the
tidyverseit is also important to know that foundational aspects, common to many languages, exist and can be added to data science workflows. For instance, class, functions, and data simulation all have an important role to play.
Key libraries and functions
- Base R
|“or”&“and”|>“pipe”$“extract”as.character()as.integer()c()citation()class()function()head()library()max()mean()print()rnorm()round()runif()sample()set.seed()sum()
- Core
tidyverse[@tidyverse]dplyr[@citedplyr]arrange()case_when()count()filter()group_by()if_else()left_join()mutate()pull()rename()select()slice()summarise()
forcats[@citeforcats]as_factor()fct_relevel()
ggplot2[@citeggplot]facet_wrap()geom_density()geom_histogram()geom_point()ggplot()
readr[@citereadr]read_csv()
stringr[@citestringr]str_detect()str_replace()str_squish()
tibble[@tibble]tibble()
tidyr[@citetidyr]pivot_longer()pivot_wider()
- Outer
tidyverse[@tidyverse] (these need to be loaded separately e.g.library("haven"))haven[@citehaven]read_dta()
lubridate[@GrolemundWickham2011]ymd()
janitor[@janitor]clean_names()
Background
In this chapter we focus on foundational skills needed to use the statistical programming language R [@citeR] to tell stories with data. Some of it may not make sense at first, but these are skills and approaches that we will often use. You should initially go through this chapter quickly, noting aspects that you do not understand. Then come back to this chapter from time to time as you continue through the rest of the book. That way you will see how the various bits fit into context.
R is an open-source language for statistical programming. You can download R for free from the Comprehensive R Archive Network (CRAN). RStudio is an Integrated Development Environment (IDE) for R which makes the language easier to use and can be downloaded for free from Posit here.
The past ten years or so have been characterized by the increased use of the tidyverse. This is “…an opinionated collection of R packages designed for data science. All packages share an underlying design philosophy, grammar, and data structures” [@tidyversewebsite]. There are three distinctions to be clear about: the original R language, typically referred to as “base”; the tidyverse which is a coherent collection of packages that build on top of base, and other packages.
Essentially everything that we can do in the tidyverse, we can also do in base. But, as the tidyverse was built especially for data science it is often easier to use, especially when learning. Additionally, most everything that we can do in the tidyverse, we can also do with other packages. But, as the tidyverse is a coherent collection of packages, it is often easier to use, again, especially when learning. Eventually there are cases where it makes sense to trade-off the convenience and coherence of the tidyverse for some features of base, other packages, or languages. Indeed, we introduce SQL in ?@sec-store-and-share as one source of considerable efficiency gain when working with data. For instance, the tidyverse can be slow, and so if one needs to import thousands of CSVs then it can make sense to switch away from read_csv(). The appropriate use of base and non-tidyverse packages, or even other languages, rather than dogmatic insistence on a particular solution, is a sign of intellectual maturity.
Central to our use of the statistical programming language R is data, and most of the data that we use will have humans at the heart of it. Sometimes, dealing with human-centered data in this way can have a numbing effect, resulting in over-generalization, and potentially problematic work. Another sign of intellectual maturity is when it has the opposite effect, increasing our awareness of our decision-making processes and their consequences.
In practice, I find that far from distancing you from questions of meaning, quantitative data forces you to confront them. The numbers draw you in. Working with data like this is an unending exercise in humility, a constant compulsion to think through what you can and cannot see, and a standing invitation to understand what the measures really capture—what they mean, and for whom.
@kieranskitchen
R, RStudio, and Posit Cloud
R and RStudio are complementary, but they are not the same thing. @vistransrep explain their relationship by analogy, where R is like an engine and RStudio is like a car—we can use engines in a lot of different situations, and they are not limited to being used in cars, but the combination is especially useful.
R
R is an open-source and free programming language that is focused on general statistics. Free in this context does not refer to a price of zero, but instead to the freedom that the creators give users to largely do what they want with it (although it also does have a price of zero). This is in contrast with an open-source programming language that is designed for general purpose, such as Python, or an open-source programming language that is focused on probability, such as Stan. It was created by Ross Ihaka and Robert Gentleman at the University of Auckland in the 1990s, and traces its provenance to S, which was developed at Bell Labs in the 1970s. It is maintained by the R Core Team and changes to this “base” of code occur methodically and with concern given to a variety of different priorities.
Many people build on this stable base, to extend the capabilities of R to better and more quickly suit their needs. They do this by creating packages. Typically, although not always, a package is a collection of R code, mostly functions, and this allows us to more easily do things that we want to do. These packages are managed by repositories such as CRAN and Bioconductor.
If you want to use a package, then you first need to install it on your computer, and then you need to load it when you want to use it. Dr Di Cook, Professor of Business Analytics at Monash University, describes this as analogous to a lightbulb. If you want light in your house, first you need to fit a lightbulb, and then you need to turn the switch on. Installing a package, say, install.packages("tidyverse"), is akin to fitting a lightbulb into a socket—you only need to do this once for each lightbulb. But then each time you want light you need to turn on the switch to the lightbulb, which in the R packages case, means drawing on your library, say, library(tidyverse).
Dr Di Cook is Professor of Business Analytics at Monash University. After earning a PhD in statistics from Rutgers University in 1993 where she focused on statistical graphics, she was appointed as an assistant professor at Iowa State University, being promoted to full professor in 2005, and in 2015 she moved to Monash. One area of her research is data visualization, especially interactive and dynamic graphics. One particularly important paper is @buja1996interactive which proposes a taxonomy of interactive data visualization and associated software XGobi.
To install a package on your computer (again, we will need to do this only once per computer) we use install.packages().
install.packages("tidyverse")And then when we want to use the package, we use library().
library(tidyverse)Having downloaded it, we can open R and use it directly. It is primarily designed to be interacted with through the command line. While this is functional, it can be useful to have a richer environment than the command line provides. In particular, it can be useful to install an Integrated Development Environment (IDE), which is an application that brings together various bits and pieces that will be used often. One common IDE for R is RStudio, although others such as Visual Studio are also used.
RStudio
RStudio is distinct to R, and they are different entities. RStudio builds on top of R to make it easier to use R. This is in the same way that one could use the internet from the command line, but most people use a browser such as Chrome, Firefox, or Safari.
RStudio is free in the sense that we do not pay for it. It is also free in the sense of being able to take the code, modify it, and distribute that code. But the maker of RStudio, Posit, is a company, albeit it a B Corp, and so it is possible that the current situation could change. It can be downloaded from Posit here.
When we open RStudio it will look like Figure 1.
The left pane is a console in which you can type and execute R code line by line. Try it with 2+2 by clicking next to the prompt “>”, typing “2+2”, and then pressing “return/enter”.
2 + 2[1] 4
The pane on the top right has information about the environment. For instance, when we create variables a list of their names and some properties will appear there. Next to the prompt type the following code, replacing Zahid with your name, and again press enter.
my_name <- "Zahid"The <-, or “assignment operator”, allocates "Zahid" to an object called “my_name”. You should notice a new value in the environment pane with the variable name and its value.
The pane in the bottom right is a file manager. At the moment it should just have two files: an R History file and a R Project file. We will get to what these are later, but for now we will create and save a file.
Run the following code, without worrying too much about the details for now. And you should see a new “.rds” file in your list of files.
saveRDS(object = my_name, file = "my_first_file.rds")Posit Cloud
While you can and should download RStudio to your own computer, initially we recommend using Posit Cloud. This is an online version of RStudio that is provided by Posit. We will use this so that you can focus on getting comfortable with R and RStudio in an environment that is consistent. This way you do not have to worry about what computer you have or installation permissions, amongst other things.
The free version of Posit Cloud is free as is no financial cost. The trade-off is that it is not very powerful, and it is sometimes slow, but for the purposes of getting started it is enough.
Getting started
We will now start going through some code. It is important to actively write this all out yourself.
While working line-by-line in the console is fine, it is easier to write out a whole script that can then be run. We will do this by making an R Script (“File” -> “New File” -> “R Script”). The console pane will fall to the bottom left and an R Script will open in the top left. We will write some code that will get all of the Australian federal politicians and then construct a small table about the genders of the prime ministers. Some of this code will not make sense at this stage, but just type it all out to get into the habit and then run it. To run the whole script, we can click “Run” or we can highlight certain lines and then click “Run” to just run those lines.