---
title: "Introduction to R studio"
runningheader: "Tufte Handout with R Markdown" # only for pdf output
subtitle: "Tufte Handout with R Markdown" # only for html output
author: "DATASCI 120 Teaching Team"
date: "`r Sys.Date()`"
output:
  tufte::tufte_html: default
  tufte::tufte_handout: 
    citation_package: natbib
    latex_engine: xelatex
  tufte::tufte_book:
    citation_package: natbib
    latex_engine: xelatex
bibliography: skeleton.bib
link-citations: yes
---

```{r setup, include=FALSE}
library(tufte)
library(ggplot2)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
```
# R and R studio
- R is a programming language for data analysis and statistical computing
- R studio is an environment for the R language that provides user-friendly interface

# Installation 
Even if you use RStudio, you’ll still need to download R to your computer. RStudio helps you use the version of R that lives on your computer, but it doesn’t come with a version of R on its own.

- download and install R at <https://cran.r-project.org>
- download and install R studio at <https://rstudio.com/products/rstudio/download/#download>

# Install and load packages
Currently, the CRAN package repository features 20646 available packages.

- In RStudio's console, install a package named packageName with the command `install.packages("packageName")`. This command only needs to be run once for each package. 
- Or, click the install button under Rstudio's Packages tab, select install from repository, and enter the packageName. 
- Load the package with `library(packageName)` at the start of each new R session when you plan to use the package. You can load packages in Rstudio's Console, an R script file, or an R markdown file.

# R Markdown
This is an R Markdown document. It is a file format in R that lets you mix text, figures, R code, and the code's results in one document, which can be HTML, PDF, or MS Word. When you click the **Knit** button a document will be generated. 

For more details on using R Markdown see the NYTcovid files on Canvas, as well as <http://rmarkdown.rstudio.com>.

# Tufte handout style

- Install by running `install.packages("tufte")` in the Rstudio Console.
- To make a new R Markdown document using Tufte style: Go to File > New File > R Markdown > From template > Tufte Handout.
- Below, we list a few commonly used features. For more examples, see the Rstudio Tufte Handout template. 

The Tufte handout style is a style that Edward Tufte uses in his books and handouts. Tufte's style is known for its extensive use of sidenotes, tight integration of graphics with text, and well-set typography. 

Any use of a footnote will automatically be converted to a sidenote.^[This is a sidenote that was entered using a footnote.] 

To place ancillary information in the margin without the sidenote mark (the superscript number), you can use the `margin_note()` function. `r margin_note("This is a margin note.  Notice that there is no number preceding the note.")`

Or, you can write a chunk starting with ```` ```{marginfigure} ```` instead of R code chunks ```` ```{r} ````. See an example on the right about the first fundamental theorem of calculus.
```{marginfigure}
We know from _the first fundamental theorem of calculus_ that for $x$ in $[a, b]$:
$$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$
``` 

By default, figures are placed in the main column.

When you want a margin figure, all you need to do is the chunk option `fig.margin = TRUE`.

```{r fig-margin, fig.cap="simple margin picture.", fig.height=3.5, fig.margin=TRUE, fig.width=3.5, message=FALSE, cache=TRUE}
a <- c(1:10)
plot(a)
```

When you want a full-width figrue, set `fig.fullwidth = TRUE`.
```{r fig-full, fig.cap="simple full-width picture.", fig.fullwidth = TRUE, fig.height=3.5, fig.width=10, message=FALSE, cache=TRUE}
a <- c(1:10)
plot(a)
```

This style provides first and second-level headings (that is, `#` and `##`), demonstrated in the next section. You may get unexpected output if you try to use `###` and smaller headings.

References can be displayed as margin notes for HTML output. For example, we can cite R here [@R-base].
```{r bib, include=FALSE}
# create a bib file for the R packages used in this document
knitr::write_bib(c('base', 'rmarkdown'), file = 'skeleton.bib')
```

```{marginfigure}
In R, both `=` and `<-` can be used for assigning a value to variables.
```
```{marginfigure}
R uses 1-indexing, meaning that the indexing of elements in vectors and matrices starts at 1, not 0 as in some other programming languages.
```

# Vectors

```{r vector}
vector_a <- c(1:10)
cat("vector_a:", vector_a,'\n') 
#cat stands for "concatenate and print"
vector_b <- seq(1, 10, by=2)  
# Create a vector with a sequence of numbers
cat("vector_b:", vector_b,'\n')
vector_c <- rep(2, length(vector_b))  
# Replicate 2, matching the length of vector_c
cat("vector_c:", vector_c,'\n')
vector_d <- vector_b + vector_c 
# Element-wise addition of vectors
cat("vector_d:", vector_d,'\n')
```

# Matrices

```{r matrix}
matrix_a <- matrix(1:9, nrow=3, byrow=TRUE)  
# A 3x3 matrix with values 1 to 9
print(matrix_a)

matrix_b <- diag(3) 
# Create a 3x3 identity matrix
print(matrix_b)

# Element-wise multiplication of matrices
element_wise_product <- matrix_a * matrix_b
print(element_wise_product)

# Matrix multiplication
product_matrix <- matrix_a %*% matrix_b
print(product_matrix)

# Applying a function to rows of a matrix
row_means <- apply(matrix_a, 1, mean)  
# Calculate mean of each row
print(row_means)

# Eigenvalues and eigenvectors of a matrix
eigen_values_vectors <- eigen(matrix_a)
print(eigen_values_vectors$values)
# Accessing eigenvectors
eigenvectors <- eigen_values_vectors$vectors
# Indexing an eigenvector, e.g., the first eigenvector
first_eigenvector <- eigenvectors[, 1]
# Print the first eigenvector
print(first_eigenvector)
```


::: {.fullwidth}
# Simple data analysis
Any content in tufte's style can span to the full width of the page. This, along with the sections that follow, serves as illustrative examples.

R includes many pre-installed datasets accessible via `data("datasetName")`. For importing your own data, such as from a CSV file, `read.csv("path/to/your/data.csv")` is commonly used.

Here are a few simple data analysis commands using the built-in dataset `mtcars`. The `mtcars` dataset contains fuel consumption data (measured in miles per gallon, or mpg) and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). The dataset includes variables such as the number of cylinders (cyl), displacement (disp), horsepower (hp), and weight (wt).

Exploratory data analysis:

```{r data}
# Load the 'mtcars' dataset
data("mtcars")

# Summary statistics of the dataset
summary(mtcars)

# Calculate the mean miles per gallon (mpg)
mean_mpg <- mean(mtcars$mpg)
cat("Average MPG:", mean_mpg)

# Simple plot: Miles per Gallon (MPG) vs. Weight (1000 lbs)
plot(mtcars$wt, mtcars$mpg, main="MPG vs. Weight",
     xlab="Weight (1000 lbs)", ylab="Miles per Gallon",
     pch=19, col="blue")
# main specifies the main title of the plot
# lab stands for label
# pch stands for "plotting character."
# It specifies the symbol used in the plot for each point.
# col stands for color
```

Statistical models:

The `lm` function comes with base R and does not require the installation of additional packages to use. It is part of R's standard statistical functions, designed to perform linear modeling, including fitting linear regression models. 

```{r lm}
# Fit a linear model: MPG ~ Weight
lm_model <- lm(mpg ~ wt, data = mtcars)
summary(lm_model)

# Print coefficients of the linear model
cat("Coefficients of the linear model:\n")
print(coef(lm_model))

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(color = "blue") +
  geom_smooth(method = "lm", color = "red", se = FALSE) +
  labs(title = "MPG vs. Weight with Regression Line (ggplot2)",
       x = "Weight (1000 lbs)",
       y = "Miles per Gallon") +
  theme_minimal()
```
:::

::: {.fullwidth}
