Chapter 2 Day one of R and RStudio

There is no accompanying reading.

Motivating scenario: Motivating scenario: You have heard about R and RStudio, and maybe used them, but want a foundation so you can know whats going on as you do more and more with it.

Learning goals: By the end of this chapter you should be able to

  • Explain why we are using R and RStudio.
  • Describe the five tips for writing code like a pro.
  • Install R and RStudio (or have access to them on RStudio cloud).
  • Install the R packages.
  • Open and save an R script.
There is no external reading for this chapter, but watch the required videos embeded throughout. Then go to canvas to complete the quiz for this content.

2.1 What is R and why / how do we use it?

R is a computer program, which is the go to language for most statisticians and data scientists (although some prefer python or julia). R makes it possible to conduct complex statistical analyses, make nice figures, and write this book, all in one environment.

As opposed to GUI’s, like Excel, or click-based stats programs, R is focused around writing and sharing scripts. This allows analyses to be shared and replicated, ensures that data manipulation occurs in a script, preserving the integrity of the original data, and allows for tremendous flexibility.

2.2 Why use R?

  • R is free.
  • There are many “packages” in R for specialized analyses.
  • R can make nice graphics.
  • While learning R is not easy, inexperienced programmers can quite quickly do useful things. You will be able to make nice plots and summarize data by next week!
  • Using R (or any scripting based analysis) allows us to save all the steps of our analysis, making our work easy to reproduce, describe, and build off of.

FIGURE 2.1: Watch this video about why and how to R (6 min and 10 sec), from STAT 545 – a grad level data science class at the University of British Columbia. We will borrow from this course occasionally.

2.2.1 What is RStudio?

More precisely, R is a programming language that runs computations, while RStudio is an integrated development environment (IDE) that provides an interface by adding many convenient features and tools. So just as the way of having access to a speedometer, rearview mirrors, and a navigation system makes driving much easier, using RStudio’s interface makes using R much easier as well.

In addition to being a great place to use R, RStudio is a Certified B corporation, which offers many great resources we will rely on over this term. RStudio has a freemium business model, and you will not need to pay for any of RStudio’s products this term.

2.2.2 What is the tidyverse?

A great part about R is that many people have written packages to help with specific tasks.

The tidyverse refers to both a set of packages, and a way to do things in R. The tidyverse packages we use the most in this course are:

  • ggplot2: For making plots.
  • dplyr: For summarizing and handling data.
  • tidyr: For converting data from wide to long format (and vice versa).
  • readr: For reading in data.
  • forcats: For controlling the order of categorical variables.

We will use the tibble, stringr, and purrr packages less often if at all (although I use them often). If you are using your computer, rather than RStudio Cloud, you will need to install tidyverse the first time you use it.

The tidyverse is an opinionated collection of R packages... shar[ing] an underlying design philosophy, grammar, and data structures. - [tidyverse.org](https://www.tidyverse.org/)

FIGURE 2.2: The tidyverse is an opinionated collection of R packages… shar[ing] an underlying design philosophy, grammar, and data structures. - tidyverse.org

You will see that there are many ways to do things in R. Over years of teaching this course I have switched to teaching predominantly using tidyverse tools.

One major reason for this is that the focus on a shared and coherent philosophy, grammar and data structure makes the tidyverse easier to teach and learn than base R. However, there are still challenges to learning and teaching the tidyverse, the two major challenges are

  1. It takes time to learn and appreciate the shared philosophy and data structure.
  2. Many people first learned R using base R, so it can be frustrating to start to learn again.

Overcoming challenge (1) takes time but is helped by reflecting on why and how code works when it works, and fails when it fails (rather than copying and pasting code that works), and continually asking questions.

Overcoming challenge (2) can be tough, but I believe it’s well worth it. Amelia McNamara’s R syntax comparison cheat sheet can help .

FIGURE 2.3: Watch this video about the goals I have for the next week of R content (3 min and 15 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

2.3 Observations and suggestions for learning R / computer stuff

Teaching this class for years, I’ve learned a few things about learning R that you should know.

FIGURE 2.4: Watch this video about how to succeed in R (5 min and 48 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

2.3.1 Observations

  • Some people pick R up fast, other slowly.
  • The speed at which students get familiar with R is unrelated to intelligence.
  • Everyone who keeps trying gets there eventually.
  • Despair and feeling low/dumb are the things that get people jammed up.

2.3.2 Suggestions

  • Don’t worry. Keep trying. But TAKE BREAKS.
  • Step away from the computer as much as possible, code & make plans on scratch paper.
  • Be patient & understanding with yourself and your friends.
  • Be creative.
  • Ask for help.
  • When something works (or it doesn’t) take time to figure out how / why.
  • Fight the urge to compare yourself (negatively or positively) to others.

At last year’s RStudio conference, Hadley Whickham, conrasted the “automatic negative thoughts” we feel some time in coding to the “balanced alternative” that we want to get to.

2.4 Installing R (or not)

FIGURE 2.5: Watch this video about accessing R and RStucio (6 min and 38 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

We use R version 4.2.0 or above, and tidyverse version 1.3.0 or above.
You can either download and install R, RStudio, and tidyverse onto your computer (see Installing RStudio for more info), or you can do all the coursework with RStudio Cloud without installing anything on your computer (see Getting on RStudio Cloud for more info). In general, RStudio cloud cannot handle the whole terms worth of computing hours, so if you choose this option, you might need to pay a few bucks or I could see if I could support some of you with my existing RStudio cloud credits.

2.4.1 Getting on RStudio Cloud

Using RStudio Cloud allows you to use R and RStudio without installing anything on your computer.

Advantages to RStudio Cloud

  • From my experiencing teaching this course, about 5% of students have computers or computer systems where installing R is challenging, now you don’t have to.

  • Some students have older computers with limited computation. For them, a few class exercises (involving large-scale permutation or simulation) go super slow, and they can get justifiably frustrated.

  • Some computer setups make installing tidyverse or other specific R packages somewhat painful. RStudio Cloud removes this pain.

Disadvantages to RStudio Cloud

  • The biggest disadvantage of RStudio cloud is that it’s expensive if we all use it and I only paid for a certain amount of usage, so please use it only if you’re having issues using R on your computer. Please e-mail me if you would like to use it!
  • Sometimes the system can get overwhelmed. This is pretty rare, but once a student was trying to use RStudioCloud during the international RStudio convention. The RStudio Cloud could not handle all the traffic and went down that day.
  • You need an internet connection to use R. This can be a bummer if you don’t always have a reliable one.
  • Some people (🖐) like having everything on their computer and struggle thinking about / working with folders on a cloud.

2.4.2 Installing RStudio

  1. First download/update R from here, be sure to download the version compatible with your computer, and pick any CRAN mirror you like (I usually do Iowa). If you installed R a while ago, be sure you’re using R version 4.0.0 or above.

  2. Then download/update RStudio from here. Be sure to select the free version (RStudio Desktop, Open Source License), and as above, be sure to download the version compatible with your computer. If you installed RStudio a while ago, be sure you’re using RStudio version 1.3.0 or above.

Advantages to downloading and installing RStudio

  • You can do a bunch without stable internet.
  • You are not reliant on a cloud service which could go down.
  • Everything is on your computer.
  • You learn the joys (and frustrations, and how to overcome them) of dealing with packages, loading data etc… .

Disadvantages to downloading and installing RStudio

2.5 The RStudio IDE

2.5.1 A tour of the RStudio IDE.

FIGURE 2.6: Watch this video about a tour of RStudio (1 min and 53 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

Customize settings and preferences in the RStudio IDE.

Suggested preferences for RStudio IDE.

Suggested preferences for RStudio IDE.

FIGURE 2.7: Suggested preferences for RStudio IDE.

After you open RStudio, navigate to Preferences under the RStudio tab. Set yours to be like mine (Fig: 2.7), below and then click apply.

Feel free to set Code, Appearance, Pane Layout etc to however you like!

2.6 Tidy data

FIGURE 2.8: Watch this video about tidy data (4 min and 02 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

Above we introduce the tidyverse ecosystem of tools for R. Tidyverse tools can be useful and general because they rely on a certain and predictable data structure known as “tidy data.”

Characteristics of tidy data

  • Each variable must have its own column.
  • Each observation must have its own row.
  • Each value must have its own cell.

A major benefit of the tidy data structure is that when data structure is reliable, we can deal with diverse data sets in a consistent way.

2.7 Intro to R

2.7.1 Assigning variables in R

FIGURE 2.9: Watch this video about assignment and good names in R (4 min and 00 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

We can mess around typing things in R all we want. But R doesn’t know we did anything until we “assign” something to a variable. We do this with the assignment operator <-. For example

my_name <- "Yaniv Brandvain"
one     <- 1

Now R knows that my_name is yaniv brandvain . Notice I put my name in quotes to tell R that we are dealing with a word (or character), a not around my_name because my_name and one are variables, and ” is a character, and not a variable in R) and the “yaniv brandvain” is a character. On the other hand, there is no need to wrap quotes around numbers (unless you want R to think the number is a character).

We can see that R knows these things by typing them.

my_name
## [1] "Yaniv Brandvain"
one
## [1] 1

All variables assigned should be in your environment window, or you can use the ls() function to ask R for them.

ls()
## [1] "my_name" "one"

2.7.2 Using functions in R

FIGURE 2.10: Watch this video about using functions in R (3 min and 13 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

We use functions to do things in R. A function usually takes one (or more) argument(s) and returns a thing. For example,

  • The round() function rounds a value (or vector of values) to the nearest digit you specify. e.g., round(x = 9.32, digits = 1) returns 9.3.
  • The help() function to learn more about a given function. For example help(round) will return this (Fig: 2.11).

FIGURE 2.11: An example of R help

Throughout the text, I include a hyperlink to the help for every function I introduce. There is no need to look into all of these, but it is a good practice to look at the when you are confused. Unfortunately it takes a bit of practice / knowledge to make sense of R’s help. So, check out this reference to figure out how to get the most from R’s help.

The tab button is very useful when we deal with functions. Hitting tab as you begin to type a function’s name will give suggested functions, with a brief description, while hitting tab inside the parentheses of a function will show the arguments the function takes.

You do not need to give the arguments name if we don’t want – by default R processes arguments by the order it expects them. So sqrt(x = 4), returns 2, as does sqrt(4). But it’s usually a good practice to do so, especially when there are more than two arguments as this makes it easier to understand your code and harder to mess up.

2.8 Loading, installing, and using packages

FIGURE 2.12: Watch this video about using functions in R (6 min and 35 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

In Section 2.2.2 we introduced the idea that people have developed packages to extend R to do a bunch of stuff, and in Section 3.2.3, we saw that we install an R package with the install.packages() function.

We only need to install a package once, but we need to load all packages we are using every time we open a new R session. Use the library() function to do so.

So, for example, type the following to load the tidyverse package

You should see messages like I did upon loading the tidyverse library. You should also see in the Packages tab, that you now have a check next to dplyr, forcats, ggplot2, purrr, readr tibble, and tidyr, as these are all loaded with tidyverse.

2.8.1 Reading data into R

FIGURE 2.13: Watch this video about getting data into R (4 min and 05 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

One of the most important functions we’ll use is readr::read_csv() from the readr package. (note its good practice to specify the package a function comes from followed by two colons and then the function name - although this is not always needed). readr::read_csv() takes the argument file which directs R to the file location. For now we’ll deal with files located on the internet.

library(readr)
data_link <- "https://raw.githubusercontent.com/ybrandvain/datasets/master/FlowerColourVisits.csv"
flower_visits  <- readr::read_csv(file = data_link) # get the data into R and assign it to flower visits
## Rows: 50 Columns: 3
## ── Column specification ───────────────────────────────
## Delimiter: ","
## chr (2): flower, colour
## dbl (1): number.of.visits
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

2.8.2 Vectors and Tibbles in R

FIGURE 2.14: Watch this video about data types and using the glimpse() function to figure out your data types (4 min and 49 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

Most of what we do in R starts with a vectors – a combination of simple entities. We already came across a few simple vectors of length one – for example, the number, 1 and my_name, above.

Vectors are often longer than length one, for example, we could store the names of all students in the vector student_names.

Usually vectors come linked together each as columns in a tibble (a special type of data frame). When data are tidy, each column (aka vector) is a varble, and each row describes an observation.

Classes of Vectors in R

All entries in a vector must be of the same class. The three most relevant classes are:

  • numeric – Contains numbers which can take any value. For example c(1, 2, 3) returns 1, 2, 3.
    logical – Contains logical statements. For example, c(TRUE, FALSE, FALSE) returns TRUE, FALSE, FALSE.
  • character – Contains letters, words, and/or phrases. For example c("The dog", "jumped", "over", "the moon") returns The dog, jumped, over, the moon.

You may also come across two other classes of vectors:

  • factor – This is a lot like a character, with the caveat that they are coded by numbers in R’s brain (see below). This can sometimes make things tough, so be careful, and consider when things are not working right that maybe you have factor when you thought you had a character.
  • integer – A number that must take an integer value. For example as.integer(c(1, 2.1, 3)) returns 1, 2, 3.

The dplyr::glimpse() function takes a tibble as an argument and shows us the data type of each column, as well as the first few values for that variable.

dplyr::glimpse(flower_visits)
## Rows: 50
## Columns: 3
## $ flower           <chr> "F1", "F2", "F3", "F4", "F5"…
## $ colour           <chr> "red", "white", "yellow", "o…
## $ number.of.visits <dbl> 48, 16, 29, 21, 5, 68, 20, 9…

2.8.3 Writing R scripts and beyond

FIGURE 2.15: Watch this video about writing scripts in R (7 min and 34 sec). Note this is part of an intro to R series I am developing for CBS – comments appreciated

A great thing about R is that you can remember and share exactly what you have done by saving your work as a script. In doing so it’s best practice to type your name, date and the goal of the analysis at the top (with a # to tell R this isn’t code), plus a description of your goals. Regular comments throughout, help make your code more usable.

To make a new R Script, click on File, then New File, and then R Script.

References

Ismay, Chester, and Albert Y Kim. 2019. Statistical Inference via Data Science: A ModernDive into r and the Tidyverse. CRC Press.