---
title: "Introduction to R"
author: "Rian DeFaccio, for BH Analytics LLC"
date: "`r Sys.Date()`"
format: pdf
---

```{r setup, include=FALSE}
knitr::opts_knit$set(warning = FALSE, message = FALSE)
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
```

```{r include=FALSE}
# load libraries and adjust settings
options(scipen=999)
```

## Overview

------------------------------------------------------------------------

This section serves as an introduction to doing exploratory data analysis with R and RStudio. You will get some initial exposure to all of the following:

-   What is R and RStudio
-   How to use R scripts and Quarto notebooks
-   Variables, Assignment, and the R Environment
-   R's Working Directory
-   Importing CSV Files
-   Introduction to Data Frames
-   Making Your First Plots!

## The R Programming Language

------------------------------------------------------------------------

> *"R is a language and environment for statistical computing and graphics."*
>
> it includes *"a well-developed, simple and effective programming language which includes conditionals, loops, user-defined recursive functions and input and output facilities."*
>
> *"Many users think of R as a statistics system. We prefer to think of it as an environment within which statistical techniques are implemented. R can be extended (easily) via packages."*
>
> \- From the **R FAQ**
>
> 🌐 <https://www.r-project.org/about.html>

There are now thousands of R packages to choose from to extend the functionality of R!

#### Why Use R?

Why do we use R for statistics and analysis? Well, it:

-   Is open source and free!
-   Works on Mac/Linux/Windows.
-   Has the most comprehensive network of statistical packages anywhere (20,087 hosted on CRAN as of November 22, 2023).
-   Has **state-of-the-art** data visualization capabilities.
-   Has new things implemented quickly.

Quotes from some influential people:

> *"R has had a revolutionary effect on the way statistics are communicated."*
>
> \- John Chambers (Creator of S and Co-creator of R)

> *"I like \[R\] because it's very easy to program in from a more computer science-y level. R has gotten faster over time and serves as a glue language for piecing together different data sets, tools, or software packages."*
>
> \- Roger Peng (Professor of Biostatistics at University of Texas - Austin)

#### Downloads

We assume that you have already downloaded and installed R and RStudio. For review, here are some instructions on how to do that:

-   Download R and install on your computer.
    -   🌐 [www.r-project.org](www.r-project.org)
-   Download RStudio and install on your computer.
    -   🌐 <https://posit.co/download/rstudio-desktop/>

## Introduction to RStudio

------------------------------------------------------------------------

Your instructor will now give you a tour of the RStudio IDE. What is an IDE you ask???

An **IDE (Interactive Development Environment)** is a piece of software that makes writing and debugging code easier.

You will explore the following elements of RStudio:

-   the source pane
-   the console
-   the environment explorer
-   some other miscellaneous panes

Then you will open the file *r_files/my_first_r_script.R* and learn about how R scripts work.

## Quarto Notebooks

------------------------------------------------------------------------

Also, we are currently working out of a type of file called an Quarto notebook (file extension *.qmd*). We will discover the functionality of this type of document throughout the week, but let's cover some basics now. First, there are three types of content within a notebook:

-   **YAML Metadata:** This contains data about how to compile the notebook. We will learn more about this later.
-   **Markdown:** Markdown is a lightweight markup language used for formatting text.
-   **Code Cells:** It is inside of code cells that you can run R code and view outputs.

For your reference, here is a markdown cheat sheet:

🌐 <https://www.markdownguide.org/cheat-sheet/>

There are two ways to view and work with your Quarto notebooks in RStudio:

-   **Source Mode:** Allows you to see the underlying markdown of the document.
-   **Visual Mode:** Allows you to see the formatted version of the notebook (aka the "final product")

### 🛠️Coding Practice: Working with Markdown

Take a moment to switch your Quarto viewing to source mode and then try to implement the following markdown elements in the next section.

-   Create a third-level header called "My Sand Box".
-   Create a paragraph of text with some italicized text, some bold text, and some text formatted as code.
-   Then, create an un-ordered list of your choice.
-   Finally, use markdown syntax to get the following image to display in your notebook: *../common/i_love_markdown.png*
-   **BONUS:** If you finish early, try to recreate the following table using markdown syntax:

![](images/markdown_table-01.png)

Start your work here and delete the ellipses as you go:

...

...

...

...

...

...

...

...

...

**END OF EXERCISE**

------------------------------------------------------------------------

## Variables and Assignment

------------------------------------------------------------------------

We will now start to dig into doing some programming!

We did some math and created some variables in our first R script, but let's formalize some of these ideas.

To create variables we use an assignment operator.

We will `<-` in this class. It takes the result of some code on the right side and *assigns* it to a variable named on the left side.

```{r}
my_log <- log(10, base = 4)
```

Lets assign some variables to answer the following question: *What is the BMI of someone who is 6 ft 2 inches tall and weighs 210 pounds?*

```{r}
weight   <- 210 
height   <- (12*6) + 2 
constant <- 703 
bmi      <- (weight * constant)/height ^ 2 
```

Where's the answer?

By default, no output to the console is provided when assignments are made. You may request the output by typing the variable's name in the console.

```{r}
bmi
```

R is not verbose by default.

Lets now consider the following: *What is the BMI of this person if they lost 20 pounds?*

```{r}
weight <- weight - 20 
bmi 
```

What happened? We changed the variable `weight` but the variable `bmi` did not change.

```{r}
bmi <- (weight * constant)/height ^ 2 
bmi 
```

What does this imply about R variables?

If changes are made to intermediate variables, all downstream variables must be recalculated.

## R Functions

------------------------------------------------------------------------

First, let's define what a function is, and how to use on in R.

> *"In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed."*
>
> \- Wikipedia

To use a function is to *call a function*. Some notes about doing this in R:

-   Use the following notation: `function_name(argument1, argument2, …)`
-   To call a function, place parenthesis after the name of the function.
-   Optionally, you can also pass in additional arguments (sometimes called parameters).

In the following example, we will call/use the `print()` function.

```{r}
print("Nice, you just used the print function!")
```

## The R Environment

------------------------------------------------------------------------

The R environment contains all of the R variables/objects you have created during your current R session.

We can use the `ls()` function to view all of the objects in your R environment right now.

```{r}
ls() 
```

To remove an object from the environment use the `rm()` function.

```{r}
rm("bmi") 

# what's left?
ls()  
```

If we're to request the object `bmi` now we would get an error.

To remove all objects from the environment use the following code:

```{r}
# Etch-A-Sketch End of The World!  
# Clear the whole workspace! 
rm(list = ls()) 
ls() 
```

Anytime you define a variable using `<-` it is added to your R environment.

## Working Directory

------------------------------------------------------------------------

Your working directory is the folder that R looks to for importing external data. You can check your current working directory as follows:

```{r}
getwd()
```

Notice that the working directory for notebook chunks might be different than the working directory in the console. Try typing `getwd()` in the console and see if there is a difference.

You can check the contents of your working directory using the `dir()` function.

```{r}
dir()
```

You can check the contents of other folders by passing in file paths to the `dir()` function surrounded by quotation marks (either single or double are fine).

We are going to rely on relative file paths in this class. This means that R will use your working directory as the starting point for any file path it encounters.

Moving "down" the file tree is straightforward, name the folder you would like to go to. Moving up, is also easy, use the `..` to specify that you would like to move up a level (aka to a parent folder).

```{r}
dir('..')
```

### 🛠️Coding Practice: List Contents of a Folder

Can you list the contents of the data folder?

```{r}
# ANSWER HERE

```

Can you determine how many CSV files are in that folder based on the output?

**END OF EXERCISE**

------------------------------------------------------------------------

## Importing CSV Files

------------------------------------------------------------------------

Now that we know what our working directory is, let's import some data!

This is a data analysis class after all! 😄

Here is some code that will import data stored in a comma separated file (CSV) in the *data/* folder.

The first line imports the data and saves it to a variable called `df_gapminder` and the second line prints that variable to the screen. We use the `head()` function to only view the first few rows from this variable.

```{r}
df_gapminder <- read.csv('../data/gapminder.csv')
head(df_gapminder)
```

### 🛠️Coding Practice: Import Another Data Set

Try importing another data set from the *data/* folder, saving to a variable, and then printing it to the screen. Be careful, don't call it `df_gapminder`!

```{r}
# ANSWER HERE

```

**END OF EXERCISE**

------------------------------------------------------------------------

## Introduction to Data Frames

------------------------------------------------------------------------

Let's now talk about what type of variable we just created.

That variable is called a Data Frame. This is a popular data structure for storing tabular data (ie. data with rows and columns).

Take another look at the gapminder data frame we created earlier. See if you can identify all of the following elements from the output:

-   distinct rows
-   distinct columns
-   the overall number of columns and rows
-   the data type of each column (we'll learn more about this later)

```{r}
head(df_gapminder)
```

To extract the data from a particular column of a data frame, we use the dollar sign `$`, like in the next example. We then add the `[1:10]` to the end to only view the first ten values from that column.

```{r}
df_gapminder$lifeExp[1:10]
```

## Make Your First Plots!

------------------------------------------------------------------------

The purpose of this section is to get our feet wet with visualizing data!

It has been said "A picture is worth a thousand words." Thus, any statistical program must have decent graphics capabilities before we would consider it as a tool!

Plotting data generally fulfills two main roles:

-   Communicating aspects of my data to myself (We **must** explore our data before we analyze it).
-   Communicating numerical relationships I have discovered to my clients.

Extremely complex numerical relationships can be communicated with a well designed graphic. R has an excellent graphics system, and in fact many statisticians start out using R only for graphics.

#### R Plotting Functions

Let's explore how to build a plot using base R that examines the relationship between two variables from the gapminder data set.

Some base R plotting functions have descriptive names based on the type of plot they make, like `hist()`, `lines()`, or `boxplot()`.

Here we use the generic `plot()` function to build the scatter plot. The type of plot that the `plot()` function builds depends on the type of variable we pass to `plot()`.

Here we use what's called a formula (`lifeExp ~ gdpPercap`) to specify what columns from the `data=` argument should go on the x-axis and y-axis.

```{r}
# our first plot!
plot(lifeExp ~ gdpPercap, data=df_gapminder)
```

#### Graphics Parameters

There are some basic parameters that we can alter to change the appearance of our plots. To see documentation on all the available graphics parameters, see the **R documentation**.

🌐 <https://www.rdocumentation.org/packages/graphics/versions/3.6.2/topics/par>

In the next plot we will edit some graphing parameters:

```{r}
plot(lifeExp ~ gdpPercap,
     data=df_gapminder,
     pch  = 19,
     col  = "blue",
     cex  = 0.5,
     xlab = "GDP Per Capita",
     ylab = "Life Expectancy (Years)",
     main = "Are GDP Per Capita and Life Expectancy Related?")
```

### 🔍 Explore! Graphics Parameters

Some graphics parameters are more clearly named than others. Can you identify what the `plot()` parameters `pch=` and `cex=` represent? Feel free to use the previous plot to explore.

**Answer Here:**

-   `phc`:

-   `cex`:

To change global parameters that affect multiple plots, use the `par()` function. We will now set the background color for all plots to be light grey.

```{r}
par(bg = "light grey")
plot(lifeExp ~ gdpPercap, data=df_gapminder)
boxplot(gdpPercap ~ continent, data=df_gapminder)
```

#### Additional Plot Layers

We can add layers to our base plots by using additional functions called after the initial call to `plot()`. All additional elements are added sequentially to whatever is the current plot. You have to run these lines of code all together at the same time. In a notebook all lines of code also need to be in the same code cell.

In the next example we will add some text annotation after we build an initial plot.

```{r}
plot(lifeExp ~ gdpPercap, data=df_gapminder)
text("There are some outliers out here...", x = 80000, y = 40)
```

This time we will add a vertical line.

```{r}
# build initial plot
plot(lifeExp ~ gdpPercap, data=df_gapminder)

# add some text annotation
text("Add a vertical line at\nthe median value of GDP Per Capita", 
     x = 35000, y = 30)

# calculate the median gdp per capita
med_gdp <- median(df_gapminder$gdpPercap)

# add vertical line to plot
abline(v = med_gdp, col = "red")
```

If you wanted to add a linear regression trend line, you would first build a linear model, and then use the same `abline()` function to plot that line.

```{r}
## first build a simple linear model
model <- lm(lifeExp ~ gdpPercap, data = df_gapminder)

## then build the initial plot and add the trend line
plot(lifeExp ~ gdpPercap, data=df_gapminder)
abline(model, col = "salmon", lwd=3)
```

## Conclusion

------------------------------------------------------------------------

That wraps up our initial exploration of using R and RStudio for exploratory data analysis! We hope this has been illuminating and that it sparked lot's of ideas and further questions we will explore throughout the week.

## Answers to Exercises

------------------------------------------------------------------------

### 🛠️Coding Practice: Working with Markdown

```         
### My Sand Box  

Some **bold**, *italicized*, and `unicode` examples.  

* list item 1 
* list item 2 
* list item 3  

![image](../common/i_love_markdown.png)  
```

### 🛠️Coding Practice: List Contents of a Folder

```{r}
dir('../data')
```

### 🛠️Coding Practice: Import Another Data Set

```{r}
# this time we import an admissions data set 
df_admit <- read.csv('../data/admit.csv')
head(df_admit)
```

### 🔍 Explore! Graphics Parameters

-   `phc`: **This argument specifies the type of symbol to represent points on a scatter plot. For example, you could have circles, squares, or other shapes represent a point on the plot.**

-   `cex`: **The argument specifies the relative size of the points and text on a plot.**
