Description

This purpose of this module is to introduce you to RStudio and get familiar with R language. We will go over some basic functions and then you will practice with some questions.

Getting to know RStudio

What is “RStudio”?

RStudio is everything you can see in front of you right now! In technical terms, it is an IDE (or Integrated Development Environment) for the R programming language. Essentially, these four windows in front of you are your workspace in which you will use R code as a tool to “find the truth” in your data, and RStudio is a tool that organizes R code in a more “friendly” manner.

This window (that you’re reading this text in) is where you will view our module files such as Intro to R.Rmd, the file you’re in currently! The window below this is the Console, where RStudio will execute code typed into the file. To the right of these two windows are your Global Environment and the File Viewer.

Introduction to R Code

Comments

Within the file, below this line you should see a box with a little green triangle in the right-hand corner. This box is called a “code chunk”, and is what we will use to write actual code inside a file like this.

# I'm a code chunk!

You can run the code within this chunk by clicking the little green arrow. You’ll notice that clicking the arrow prints the text inside the chunk to the console below. It doesn’t do anything else, but that’s because the code above is an example of a comment, a special type of text we can use to explain what we’re doing. Comments aren’t treated as code, but are more like annotations. They don’t execute like regular code. However, it is important to document your code using comments so that you can come back to old code and see what you did, or so someone else can figure out what you’re doing just by looking at your code.

Install and load Packages

Another important tool we’ll be using is called Tidyverse.

This is a package, or a bundle of R code that simplifies the code that we have to write ourselves. Think of a package like a specific toolbox that another R user built and is giving to you to help your code. Different packages have different tools in them, much like a set of screwdrivers does something different from a set of wrenches, and some even overlap what they do.

The Tidyverse is a special R package, in that it contains many different tools, and many other packages are built off of Tidyverse code. We’re going to use the Tidyverse a lot in this course, as it is one of the best sets of tools for data cleaning. I’ll explain more of what “data cleaning” is later, for now lets run some code to load in the tidyverse package by executing the code chunk below.

# Load the tidyverse package (you may need to install it first if you don't have it in your computer yet, but once installed, every time you just need to "call" it out)

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

This code chunk uses the command library() to load the tidyverse package. There are other packages we will be using in this module. Use what you learned in the last code chunk to fill in the missing code below:

# Load the stats package (Do you need to?)


# Load the ggplot2 package
library(ggplot2)

# Load the dplyr package
library(dplyr)

# Load the readxl package
library(readxl)

Don’t forget to run the code chunk by clicking the green arrow!

How do you know you have successfully loaded the packages? Do you know another “straightforward” way of looking for and installing packages?

Probability

Random Variables and Probability Distributions

Probability Distributions of Discrete Random Variables

Now we are going to learn some functions of R with reviewing probability.

We can draw random samples from a specified set of elements is the function sample().

sample(1:10, 2)
## [1] 9 1

The function rep() means replicating the values. Remember, you can always use the Help and search for the functions or type ?rep to look for the details about the functions.

The <- symbol is called the Assignment Operator. What this means is that it takes the result of the code on the right and assigns it to the name on the left as an object.

Try the examples here.

#generate the vector of probabilities

probability <- rep(1/10, 10)

# plot the probabilities 

plot(probability,
      xlab = "outcomes",
      main = "Probability Distribution")

# generate the vector of cumulative probabilities 

cum_probability <- cumsum(probability)

plot(cum_probability, 
     xlab = "outcomes", 
     main = "Cumulative Probability Distribution") 

#generate the vector of probabilities of 1/5 and plot the probabilities and cumulative probabilities

# Vector

# plot the probabilities 


# generate the vector of cumulative probabilities 

# plot the cumulative probabilities

Bernoulli Trials

We can use the R functions to define our probability distribution. The example starts with binomial distribution with classic tossing coin. We can compute the probability for Bernoulli trials.

# observing Head 10 times when tossing a fair coin 20 times

dbinom(x = 10,
       size = 20,
       prob = 0.5) 
## [1] 0.1761971
# compute P(5 <= k <= 15) 

sum(dbinom(x = 5:15, size = 20, prob = 0.5))
## [1] 0.9881821
#or 

pbinom(size = 20, prob = 0.5, q = 15) - pbinom(size = 20, prob = 0.5, q = 4) 
## [1] 0.9881821

Try the interview example we had in class:

# A student applied 3 jobs and had the interview. The probability of getting a job offer is 0.3. For each job interview, it’s either get the offer or not. What is the probability of getting 2 job offers?



# compute P(𝑘< 3) 
# calculate the probability
p <- 0.3
k <- 2
n <- 3
binom <- choose(n, k) * (p^k) * ((1-p)^(n-k))
binom
## [1] 0.189

Discrete variable

Now if we want to look at a list of all possible outcomes that can occur and their respective probability, we can conduct the probability distribution. Still toss a fair coin 20 times and observe Head.

# set up vector of possible outcomes
k <- 0:20

# assign the probabilities
probability <- dbinom(x = k,
                      size = 20, 
                      prob = 0.5)

# plot the outcomes against their probabilities
plot(x = k, 
     y = probability,
     main = "Probability Distribution Function") 

# compute cumulative probabilities
prob <- pbinom(q = k, 
               size = 20, 
               prob = 0.5)

# plot the cumulative probabilities
plot(x = k, 
     y = prob,
     main = "Cumulative Distribution Function") 

Continuous Random Variables

Here is the example to show how to calculate the expected value and variance of a continuous random variables in R. The math functions in R is following the order of operations. Make sure putting in the right function! integrate() takes integration calculation. In order to get only a numeric value of the integral, we need to use the $ operator in conjunction with value. The $ operator is used to extract elements by name from an object of type list.

# define functions
f <- function(x) 3 / x^4
g <- function(x) x * f(x)
h <- function(x) x^2 * f(x)

# compute area under the density curve
area <- integrate(f, 
                 lower = 1, 
                 upper = Inf)$value
area 
## [1] 1
# compute E(X)
EX <- integrate(g,
                lower = 1,
                upper = Inf)$value
EX
## [1] 1.5
# compute Var(X)
VarX <- integrate(h,
                  lower = 1,
                  upper = Inf)$value - EX^2 
VarX
## [1] 0.75

The Normal Distribution

Let’s meet the standard normal distribution here. Notice that with continuous variable, the function for plotting the distribution is curve().

# draw a plot of the N(0,1) PDF
curve(dnorm(x),
      xlim = c(-3.5, 3.5),
      ylab = "Density", 
      main = "Standard Normal Density Function") 

# compute density at x=-1.96, x=0 and x=1.96
dnorm(x = c(-1.96, 0, 1.96))
## [1] 0.05844094 0.39894228 0.05844094
# plot the standard normal CDF
curve(pnorm(x), 
      xlim = c(-3.5, 3.5), 
      ylab = "Probability", 
      main = "Standard Normal Cumulative Distribution Function")

We can also use R to calculate the probability of events associated with a standard normal variate. Let us say we are interested in \(P(Z<1.2)\):

# compute the probability using pnorm()
pnorm(1.2)
## [1] 0.8849303

Statistics

Now we are using the example from the statistics part to learn how to import data and have some basic analysis with the data.

Reading Data

The data in the Gender Gap of Earnings example is in the form of .xlsx file. We can also read .csv files (note: .csv stands for “comma separated values”, you can also have .tsv (tab separated values) or other separators depending on the data you are using.) or import data from other software (SPSS, STATA, SAS) in other data forms.

# import the data into R from your folder; you may need to check your working direction first by the function getwd().
library(readxl)
cps <- read_excel('D:/cps_ch3-1.xlsx')

# this data is also available on the internet so you can import the data directly from the internet, too. 
cps <- read_excel('D:/cps_ch3-1.xlsx')

If you have a .csv file, you can use read.csv() to import data to RStudio. Don’t forget to save it to an object. Let’s try in the practice here.

# Read the gordon_data.csv file into RStudio, and save it to an object named "gdata"
gdata <-read.csv('D:/gordon_data-1.csv')

# Read the penguins.csv file into RStudio and save it to an object named "penguins"
penguins <-read.csv('D:/penguins-1.csv')

Cleaning Data

We have loaded the package dyplr which provides functions that simplify data wrangling. To begin with, let’s have a basic understanding about data cleaning.

Data cleaning, at its simplest, is taking data that may be messy or in a format that is hard to understand, and manipulating it into a form that we can understand and visualize effectively. The textbook has I’ll walk you through a few helpful functions that we will be using a lot, along with some exercises, and we’ll end with an example for you on your own!

Note: It’s important to note that our data is organized into what is known as “tidy data format”. “Tidy data” follows three simple rules:

1. Each variable must have its own column. 2. Each observation must have its own row. 3. Each value must have its own cell.

These rules are easy to use and implement, but they will save you a ton of time and headache if you follow them!

However, before we can manipulate our data, we first have to see the data! There are two ways to do this effectively, using the head() and View() functions. head() will take an object and display the first six rows, whereas View() will display the entire object in a new window.

# get an overview of the data structure; 
head('gordon_data-1.csv')
## [1] "gordon_data-1.csv"
View('gordon_data-1.csv')

Can you write some code that will display the data for the penguins object and gdata object?

# Use head() to display the penguins dataset
head('penguins-1.csv')
## [1] "penguins-1.csv"
# Use View() to display the penguins dataset
View('penguins-1.csv')
# Use head() to display the gdata dataset
head(gdata)
##    sub_id bookstore_dollars dining_hall_dollars sleep_horus studying_hours_week
## 1 sub_001                67                 126           6                  20
## 2 sub_002                80                 100           7                  10
## 3 sub_003               100                  75           8                  22
## 4 sub_004                33                 260           4                  21
## 5 sub_005                90                 109           6                  15
## 6 sub_006               100                 322           4                  16
##     major
## 1   psych
## 2    math
## 3 physics
## 4   psych
## 5   psych
## 6    math
# Use View() to display the gdata dataset
View(gdata)

Select subset data

There are several functions I want to introduce before our textbook’s example of grouping the observations. First, select(). We can use select subsets by using this function.

# Select the "a_sex" and "ahe08" columns
cps_sub_1 <- dplyr::select(cps, "a_sex", "ahe08")
head(cps_sub_1)
## # A tibble: 6 × 2
##   a_sex ahe08
##   <dbl> <dbl>
## 1     1  17.2
## 2     1  15.3
## 3     1  22.9
## 4     2  13.3
## 5     1  22.1
## 6     2  12.2
# We can use the "-" symbol (also known as the "minus" operator) to say "I want to select everything minus the a_sex column"
cps_sub_2 <- dplyr::select(cps, -"a_sex")
head(cps_sub_2)
## # A tibble: 6 × 2
##    year ahe08
##   <dbl> <dbl>
## 1  1992  17.2
## 2  1992  15.3
## 3  1992  22.9
## 4  1992  13.3
## 5  1992  22.1
## 6  1992  12.2

The penguins dataset contains a number of interesting columns about three species of penguins. However, the “X” column is simply the row number, which we don’t need. Can you write some code that selects only the “species”, “island”, “sex”, and “year” columns? Save this data to an object named penguins_sub

# Select only the "species", "island", "sex", and "year" columns, and save to penguins_sub
penguins_sub <- select(penguins, species, island, sex, year)

The Pipe function

Before we move to more complicated code, I’m going to introduce you to a little helper function that will make your life a little easier: the pipe function.

The pipe is a simple function that looks like this: %>% and performs a simple but incredibly helpful function. The pipe simply takes what is on its left-hand side and passes it into the first argument on the right-hand side. For example:

cps_sub <- dplyr::select(cps, "ahe08") and cps_sub <- cps %>% dplyr::select("ahe08") do the exact same thing.

When we stack a bunch of different functions, they would have to be nested inside one another, which could get really messy. It can be cleaned up using a pipe. That’s what we have in the textbook and we will be using the pipe from here on out to organize code.

Filtering Data with filter()

We know how to select columns using the select() function, what if we want to select only rows (or observations) that meet certain criteria? We can do this (called filtering) using the filter() function.

filter() takes a column and filters the data based on a logical expression. The simplest logical expression is the “==” operator, or the “is equal to”. For example, lets select only the observations in 1992:

# Filter only the observations from 1992 
cps_1992 <- cps %>%
  filter(year == 1992) 
head(cps_1992)
## # A tibble: 6 × 3
##   a_sex  year ahe08
##   <dbl> <dbl> <dbl>
## 1     1  1992  17.2
## 2     1  1992  15.3
## 3     1  1992  22.9
## 4     2  1992  13.3
## 5     1  1992  22.1
## 6     2  1992  12.2

Note: Remember that I’m using the pipe here to pass the cps dataset into the filter() function

What’s this code doing? In our case, the filter() function is finding every observation whose value in the year column is equal to “1992”.

Can you write code to find only penguins of the “Adelie” species and Save this data to an object named penguins_Adelie?

Note: filter() is picky about capitalization! Note: When you deal with string variables (i.e., words, not numerical), you need to use the quote sign to capture the value: "Adelie".

penguins_Adelie <-penguins%>%
  filter(species == "Adelie") 
head(penguins_Adelie)
##   X species    island bill_length_mm bill_depth_mm flipper_length_mm
## 1 1  Adelie Torgersen           39.1          18.7               181
## 2 2  Adelie Torgersen           39.5          17.4               186
## 3 3  Adelie Torgersen           40.3          18.0               195
## 4 4  Adelie Torgersen             NA            NA                NA
## 5 5  Adelie Torgersen           36.7          19.3               193
## 6 6  Adelie Torgersen           39.3          20.6               190
##   body_mass_g    sex year
## 1        3750   male 2007
## 2        3800 female 2007
## 3        3250 female 2007
## 4          NA   <NA> 2007
## 5        3450 female 2007
## 6        3650   male 2007

Rename Columns

Lets say I wanted to rename the column “a_sex” in cps to be named “gender”, we could do so with rename() like this:

cps <- cps %>%
  rename(gender = a_sex)

Can you write code to rename the “X” column in penguins to be called “row_number” instead?

Note: Remember to use “new_name” = “old_name”!

penguins <- penguins %>%
  rename("row_number" = "X")

Arranging Data

Yet another well-named function! As the name suggests, arrange() will order or arrange your data in the table based on a column, specifically in ascending order.

Here’s an example where we arrange cps based on the “ahe08” column, but first, given the explanation above, do you think this will show us the most average hour earning or the least average hour earning?

Answer Here!

Example:

cps_arr <- cps %>%
  arrange(ahe08)
head(cps_arr)
## # A tibble: 6 × 3
##   gender  year ahe08
##    <dbl> <dbl> <dbl>
## 1      1  2008  2.00
## 2      2  2008  2.01
## 3      1  1992  2.02
## 4      1  2000  2.08
## 5      2  2004  2.19
## 6      1  2000  2.31

What if we want to arrange in the opposite order, or in descending order? We simply use the desc() funtion to flip the order!

cps_arr <- cps %>%
  arrange(desc(ahe08))
head(cps_arr)
## # A tibble: 6 × 3
##   gender  year ahe08
##    <dbl> <dbl> <dbl>
## 1      1  2008  82.4
## 2      1  2008  76.9
## 3      1  2008  75.9
## 4      2  2008  74.8
## 5      1  2008  72.1
## 6      1  2008  72.1

Can you arrange gdata based on the amount of sleep each student got, starting with the student who slept the most? Save the result to a new object named gdata_arr

gdata_arr <- gdata %>%
  arrange(sleep_horus)
head(gdata_arr)
##    sub_id bookstore_dollars dining_hall_dollars sleep_horus studying_hours_week
## 1 sub_004                33                 260           4                  21
## 2 sub_006               100                 322           4                  16
## 3 sub_012               322                 100           4                  18
## 4 sub_007               126                  67           5                  17
## 5 sub_001                67                 126           6                  20
## 6 sub_005                90                 109           6                  15
##     major
## 1   psych
## 2    math
## 3    math
## 4 physics
## 5   psych
## 6   psych

Mutating Data

This is one of the most important functions we can learn. mutate() is incredibly helpful, both because it can alter an existing column, or compute an entirely new one based on the data in other columns.

Lets mutate the “ahe08” column of cps so that we get a new variable to show weekly income with working 40 hours per week:

cps_week <- cps %>%
  mutate(weekly_income = ahe08*40,
         .after = ahe08)
head(cps_week)
## # A tibble: 6 × 4
##   gender  year ahe08 weekly_income
##    <dbl> <dbl> <dbl>         <dbl>
## 1      1  1992  17.2          686.
## 2      1  1992  15.3          614.
## 3      1  1992  22.9          918.
## 4      2  1992  13.3          531.
## 5      1  1992  22.1          885.
## 6      2  1992  12.2          487.

Note: the “.after =” argument to mutate tells R to put the new column after height_cm

We have bill length and depth for every penguin in the penguins dataset. Can we calculate the total bill area for each penguin in meters? First, lets use mutate() to calculate the area (length*depth) for each penguin in a new column named “bill_area_mmsq”, and then pipe into a new mutate to convert from millimeters to meters:

# Note: To convert from square millimeters to square meters we're going to have to divide by 1000x1000, or 1000000
penguins_bill <- penguins %>%
  mutate(bill_area_mmsq = bill_length_mm/bill_depth_mm,
         .after = bill_area_mmsq)
head(penguins_bill)
##   row_number species    island bill_length_mm bill_depth_mm flipper_length_mm
## 1          1  Adelie Torgersen           39.1          18.7               181
## 2          2  Adelie Torgersen           39.5          17.4               186
## 3          3  Adelie Torgersen           40.3          18.0               195
## 4          4  Adelie Torgersen             NA            NA                NA
## 5          5  Adelie Torgersen           36.7          19.3               193
## 6          6  Adelie Torgersen           39.3          20.6               190
##   body_mass_g    sex year bill_area_mmsq
## 1        3750   male 2007       2.090909
## 2        3800 female 2007       2.270115
## 3        3250 female 2007       2.238889
## 4          NA   <NA> 2007             NA
## 5        3450 female 2007       1.901554
## 6        3650   male 2007       1.907767

Group data and summary

Our example in the textbook uses group_by() function following summarise() to compute the mean and standard deviation and number of observations for each group. This is also super helpful. We will talk more next time when we start analyze the data.

Here is the code from the textbook, giving us a quick tour of the data and compare the earnings by gender:

# group data by gender and year and compute the mean, standard deviation and number of observations for each group
avgs <- cps %>% 
        group_by(gender, year) %>% 
        summarise(mean(ahe08), 
                  sd(ahe08), 
                  n())
## `summarise()` has grouped output by 'gender'. You can override using the
## `.groups` argument.
# print the results to the console
print(avgs)
## # A tibble: 10 × 5
## # Groups:   gender [2]
##    gender  year `mean(ahe08)` `sd(ahe08)` `n()`
##     <dbl> <dbl>         <dbl>       <dbl> <int>
##  1      1  1992          23.3       10.2   1594
##  2      1  1996          22.5       10.1   1379
##  3      1  2000          24.9       11.6   1303
##  4      1  2004          25.1       12.0   1894
##  5      1  2008          25.0       11.8   1838
##  6      2  1992          20.0        7.87  1368
##  7      2  1996          19.0        7.95  1230
##  8      2  2000          20.7        9.36  1181
##  9      2  2004          21.0        9.36  1735
## 10      2  2008          20.9        9.66  1871
# split the dataset by gender
male <- avgs %>% dplyr::filter(gender == 1) 

female <- avgs %>% dplyr::filter(gender == 2)

# rename columns of both splits
colnames(male)   <- c("Sex", "Year", "Y_bar_m", "s_m", "n_m")
colnames(female) <- c("Sex", "Year", "Y_bar_f", "s_f", "n_f")

# estimate gender gaps, compute standard errors and confidence intervals for all dates
gap <- male$Y_bar_m - female$Y_bar_f

gap_se <- sqrt(male$s_m^2 / male$n_m + female$s_f^2 / female$n_f)

gap_ci_l <- gap - 1.96 * gap_se

gap_ci_u <- gap + 1.96 * gap_se

result <- cbind(male[,-1], female[,-(1:2)], gap, gap_se, gap_ci_l, gap_ci_u)

# print the results to the console
print(result, digits = 3)
##   Year Y_bar_m  s_m  n_m Y_bar_f  s_f  n_f  gap gap_se gap_ci_l gap_ci_u
## 1 1992    23.3 10.2 1594    20.0 7.87 1368 3.23  0.332     2.58     3.88
## 2 1996    22.5 10.1 1379    19.0 7.95 1230 3.49  0.354     2.80     4.19
## 3 2000    24.9 11.6 1303    20.7 9.36 1181 4.14  0.421     3.32     4.97
## 4 2004    25.1 12.0 1894    21.0 9.36 1735 4.10  0.356     3.40     4.80
## 5 2008    25.0 11.8 1838    20.9 9.66 1871 4.10  0.354     3.41     4.80

There you go! Hope you get to know RStudio a little bit better. Next time, we will learn more tools for data summary and data visualization!