Lecture 1: Introduction

Data: Breakfast cereals

Getting started

R and RStudio

  • RStudio is an Integrated Development Environment (IDE) for R. You need to download BOTH R and RStudio for RStudio to work.

  • While you can write R code without RStudio or another IDE, the interface is not as nice.

  • As a temporary alternative: you can use Posit Cloud to run RStudio online without installing anything on your computer.

R script

Start a new R script: File - New File - R Script. Do NOT choose “new project.”

Default layout of RStudio:

  • Upper left (R Script): this is a text file (.R format) that contains all the code you write
  • Lower left (Console): this is where your code is run (i.e., R will provide feedback and result here)
  • Upper right: contains information for the current R session
  • Lower right: contains information for files and packages; plots and help pages will also show up here

A few reminders:

  • When you open an R script (i.e., a .R document), make sure it’s opened in RStudio (to change the default: Right click - Get Info - Open with RStudio - Change All)
  • Have a habit of saving R script often when you are coding
  • When exit RStudio, you should only save the R script (“save workspace image?” - Don’t Save)
  • You can easily upload files to Posit Cloud, or download files from Posit Cloud

R code

Run code directly in the console:

  • you just need to hit enter in the console
  • Fast and easy
  • However: nothing is saved; can only run one line at a time

(Recommended) Write code in R scripts:

  • Can save the R scripts to run or modify your code in the future
  • Can write many lines of code and run portions of it as needed

To run code from an R script:

  • if you have any highlighted code
    • hit command + enter (mac) or ctrl + enter (windows)
    • (alternatively, you can click “Run”)
  • if you don’t have highlighted code
    • hit command/ctrl + enter
    • R will run the line of code where your cursor is at (your cursor can be anywhere in the line)
    • R will also automatically move the cursor to the next line of code
    • This is a really handy way to run code line by line

Exercise: basic math operations

To do \(\sqrt{100}\) and \(e^2\):

To do \(\ln{(1000)}\) (log base e is the default; can change the base using log(1000, base=10))

Exercise: calculate the following in R

  1. \(\frac{3\times 2 + 4^2}{5.5 \times 2}\)
  2. \(\frac{e^{5.1}+23}{\frac{3}{4} \times 5}\)
  3. \(\frac{\sqrt{12}}{\ln{(8-4.37)}}\)
Show solution

Formatting basics

  • Use # to comment out text

  • Space and empty lines, in general, do not matter in R

  • R is case sensitive!

  • Use ‘;’ to put multiple lines of code on the same line
  • Can separate one line of code into multiple lines, as long as it is obvious that the previous line has not ended

R packages

The ability to develop and use R packages is a big advantage of R over other commercial statistical software like SPSS or excel.

Before you can use a package, there are two steps:

  1. download and install the package: you only need to do this once per computer
    • How: click install under packages (recommended)
    • OR run install.packages()
  2. load the package: you need to do this each time you start a new R session
    • How: check the box under packages
    • OR run library() (recommended)
  • The Lock5Data package contains dataset from Lock, Lock, Lock, Lock, and Lock textbook Statistics: Unlocking the Power of Data

  • The tidyverse is a collection of very popular and powerful packages for data manipulation, visualization, formatting, etc.

Cereal dataset

We will explore the Cereal dataset to get more familiar with R. The code will be explained in more detail later.

  1. Create a health score of cereals with your own formula, and store it in the dataset as health.

  2. Print out the names of the cereals from the dataset.

  3. Print out information of cereals that are manufactured by Kellog.

  4. Print out information of cereals with a fiber content greater than 3 (grams per cup).

  5. Print out information of the top 5 healthy cereals according to the score health.

  6. Generate a scatterplot between Calories and health. Briefly discuss any findings (does your health score make sense based on the calories?)

Show sample code

R objects; numbers and vectors

Creating an R object

  • Examples of R object: a number, a vector, a data frame, a function, etc.

  • To assign a number to an R object called “a”:

  • These lines of code are equivalent - personal habit
  • Very useful: you can print out an R object simply by running it
    • try: highlight “a” and run it

Vector: a collection of values

  • Example: Cereal$Name is a vector of 30 values

Recall: R is case sensitive!

  • You will see these errors pretty often:
    • Object `Cereal’ not found: check spelling; check where you thought you have created this object (did you actually create it by running the code?)
    • Could not find function `Plot’: check spelling; check if you have loaded relevant package
    • ‘x’ and ‘y’ lengths differ: separately print out x and y to check
  • When creating a vector, use c( , ) for combined (concatenated) values

Vector arithmetic

  • When you apply an operation to a vector, R will perform the operation to each element in the vector
  • Important note: the vector Cereal$Calories is not changed and the new values are not stored (verify this); if you want to store the new vector, you need to assign it to a new R object or override an existing R object
  • When you do something like vector1 ± vector2, R will do the arithmetic operation element by element
    • if they have different lengths, R will give you a warning (and recycle the shorter vector)
  • R has built-in functions for common operations on vectors:

Character strings

  • Put characters in double or single quotes
  • R knows certain characters, like col = "red"

Logicals

  • TRUE (or T) and FALSE (or F) are special logical characters when NOT in quotation

  • Numerically, R treats TRUE as 1 and FALSE as 0

  • A variable with only two options, (e.g., yes/no, true/false), is referred to as a “binary,” “dichotomous,” “indicator,” or “dummy” variable

    • Example: University type (public/private); it is customary to name it public and code it as TRUE (1) for public and FALSE (0) for private
  • Exercise: create a vector, names, that contains the names of some students; create another vector, cats, that indicates if a student owns at least one cat or not

Show sample code
  • Q: what will mean(cats) return?
    Show answer The mean function will return the proportion of TRUE values in the logical vector (or, in general, 1-coded values for 0/1 variables). In this case, it will return the proportion of students who own at least one cat (i.e., 3/4 using the above sample code).
  • Logical vectors are very useful for subsetting dataset. For example, to get all the names of students who own cats:
  • Logical vectors can be created using logical operations: \(<, <=, >, >=, ==, !=\)
  • IMPORTANT: do not confuse == and =!

  • which( ) will return the INDEX of TRUE values

Vector modification and subsetting

Append to a vector

  • The easiest way to append to an existing vector is to use c( , )
  • The function append is more general. Run ?append to get more information

  • Nothing is stored! Recall, to store, you have to assign the new vector to an R object

Subset

Subsetting is the process of extracting element(s) from a vector or a dataset. The basic idea is to specify the position(s) of the elements you want, using square brackets [].

Q: what will names[c(2,2,2,3)] return?

Can also subset using a logic condition: R returns elements corresponding to TRUE

  • Alternatively, you can use the which( ) function to tell you the index position first

Delete from a vector

Use the minus sign to delete the corresponding elements from a vector

Note: tidyverse has functions to do data modification and subsetting in a more readable way (e.g., filter(), select(), mutate(), arrange()). More on this later.

Useful functions for creating vectors