Introduction to R Markdown and R Programming

Part 1: Statistical Computing

What is statistical computing?

Why R?

Why R Studio?

Why R Markdown?

Operators

# Addition
6 + 3
## [1] 9
# Subtraction
6 - 3
## [1] 3
# Multiplication
6 * 3
## [1] 18
# Division
6 / 3
## [1] 2

Operators

7 * 5
## [1] 35
7 ^ 5
## [1] 16807
7 / 5
## [1] 1.4
7 %% 5
## [1] 2
9 %% 5 #modulus (9 mod 5)
## [1] 4

R as Calculator

# Factorial
factorial(5)
## [1] 120
factorial(4)
## [1] 24
# Combination
choose(8,4)
## [1] 70
choose(4,1)
## [1] 4

R as Calculator

# Square root 
 sqrt(100)
## [1] 10
 sqrt(2)
## [1] 1.414214
# Combination
choose(8,4)
## [1] 70
choose(4,1)
## [1] 4

Comparison Operators

# Greater than
6 > 3
## [1] TRUE
# Less than
6 < 3
## [1] FALSE
# Equal to
6 == 3
## [1] FALSE
6 == 3 + 3
## [1] TRUE

Comparison Operators

# Not equal to
6 != 3
## [1] TRUE
6 < 6
## [1] FALSE
# Less than or equal to
6 <= 6
## [1] TRUE

Logical Operators

# and
(6 < 3) & (1 < 3)
## [1] FALSE
# and
(2 < 3) & (1 < 3)
## [1] TRUE
# or
(6 < 3) | (1 < 3)
## [1] TRUE
# a bit harder...
(6 < 3) | (1 < 3) & (6 < 3)
## [1] FALSE

Assigning Variables

x <- 7
x
## [1] 7
x + 3
## [1] 10
x == 7
## [1] TRUE
as.character(x)
## [1] "7"
y <- 3
x + y
## [1] 10

Data can have names

We can give names to data objects; these give us variables. Some variables are built-in:

pi
## [1] 3.141593

Variables can be arguments to functions or operators, just like constants:

pi * 10
## [1] 31.41593
cos(pi)
## [1] -1

Data can have names

We create variables with the assignment operator, <- or =

approx.pi <- 22/7
approx.pi
## [1] 3.142857
diameter <- 10
approx.pi * diameter
## [1] 31.42857

Entering Data

x <- c(7, 8, 10, 45)
x
## [1]  7  8 10 45
is.vector(x)
## [1] TRUE

Vector arithmetic

Arithmetic operator apply to vectors in a “component wise” fashion

x <- c(7, 8, 10, 45)
y <- c(-7, -8, -10, -45)
x + y
## [1] 0 0 0 0
x * y
## [1]   -49   -64  -100 -2025
length(x)
## [1] 4
length(x+y)
## [1] 4

Vector arithmetic

x + c(-7,-8)
## [1]  0  0  3 37
x^c(1,0,-1,0.5)
## [1] 7.000000 1.000000 0.100000 6.708204
2 * x
## [1] 14 16 20 90

Vector arithmetic

x > 9
## [1] FALSE FALSE  TRUE  TRUE

Logical operators also work elementwise:

(x > 9) & (x < 20)
## [1] FALSE FALSE  TRUE FALSE

Part 2: R Markdown

R Markdown

Let’s try making an RMarkdown file:

  1. Choose File > New File > R Markdown…
  2. Make sure HTML Output is selected and click OK
  3. Save the file in your new folder, call it Homework_1.Rmd.
  4. Click the Knit HTML button. After it is done, browse to the file location using the Files tab. What do you notice? Click Open in Browser to view the full HTML
  5. Change title to “Homework 1”
  6. Change author to your name in quotes
  7. Change date to the due date in quotes

R Markdown (Few things to Know)

R Code within R Markdown

You can click the green triangle in the corner to evaluate that code chunk to preview the results without compiling the entire document.

Useful Code Chunk Parameters

Parameters go into the opening brackets {r} and are separated by commas. Here are some you might find useful (checkout the guide links above for more):

R Markdown (Equations)

R Markdown (Graphs)

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00
plot(cars$speed, cars$dist)

Part 3: Vectors

Vectors

c(16, 3, 0, 7, -2)
## [1] 16  3  0  7 -2
1:5
## [1] 1 2 3 4 5

Vectors (cont’d)

# Sequence from 1 to 20, increment by 5
seq(1, 20, by = 5)
## [1]  1  6 11 16
# Repeat each element of a vector 3 times each
rep(c(1, 2), each = 3)
## [1] 1 1 1 2 2 2
# Repeat an entire vector 3 times
rep(c(1, 2), 3)
## [1] 1 2 1 2 1 2

Vectors (cont’d)

x <- 1:5
x[3]
## [1] 3
x[-4]
## [1] 1 2 3 5

Vector Arithmetic

x <- 1:5
x
## [1] 1 2 3 4 5
y <- -5:-1
y
## [1] -5 -4 -3 -2 -1
x + y
## [1] -4 -2  0  2  4
x * y
## [1] -5 -8 -9 -8 -5

Vector Arithmetic (cont’d)

x <- 1:5
x
## [1] 1 2 3 4 5
2 * x
## [1]  2  4  6  8 10
c(1, -1) * x
## Warning in c(1, -1) * x: longer object length is not a multiple of shorter
## object length
## [1]  1 -2  3 -4  5
c(1, -1) + x
## Warning in c(1, -1) + x: longer object length is not a multiple of shorter
## object length
## [1] 2 1 4 3 6

Vector Arithmetic (cont’d)

x >= 3
## [1] FALSE FALSE  TRUE  TRUE  TRUE
y < -2
## [1]  TRUE  TRUE  TRUE FALSE FALSE
(x >= 3) & (y < -2)
## [1] FALSE FALSE  TRUE FALSE FALSE
x == c(1, 3, 2, 4, 5)
## [1]  TRUE FALSE FALSE  TRUE  TRUE

Vector Arithmetic (cont’d)

x >= 3
## [1] FALSE FALSE  TRUE  TRUE  TRUE
y < -2
## [1]  TRUE  TRUE  TRUE FALSE FALSE
(x >= 3) & (y < -2)
## [1] FALSE FALSE  TRUE FALSE FALSE
x == c(1, 3, 2, 4, 5)
## [1]  TRUE FALSE FALSE  TRUE  TRUE

Boolean Vectors

x[x > 3] <- 3
x
## [1] 1 2 3 3 3
# Did not reset x
x[x > 5] <- 0
x
## [1] 1 2 3 3 3

Boolean Vectors (cont’d)

# First reset x
x <- 1:5
x
## [1] 1 2 3 4 5
sum(x >= 3)
## [1] 3
mean(x >= 3)
## [1] 0.6

Names

my_vec <- c(1, 2, 3)
names(my_vec) <- c("a", "b", "c")
my_vec
## a b c 
## 1 2 3
my_vec + 1
## a b c 
## 2 3 4

We can then access the names as their own vector by calling names() again.

names(my_vec)
## [1] "a" "b" "c"

Useful functions for vectors

If you are unclear about what any of them do, use ? before the function name to read the documentation. You should get in the habit of checking function documentation a lot!

Part 4: Matrices

Matrices

How to Create a Matrix

# Only nrow or ncol need to be specified 
A <- matrix(1:12, nrow=3, ncol=4, byrow=F)
A
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
B <- matrix(letters[1:12], nrow=3, byrow=T)
B
##      [,1] [,2] [,3] [,4]
## [1,] "a"  "b"  "c"  "d" 
## [2,] "e"  "f"  "g"  "h" 
## [3,] "i"  "j"  "k"  "l"

How to Create a Matrix

# Only nrow or ncol need to be specified 
my_matrix <- matrix(1:12, nrow = 3, ncol = 4, byrow = TRUE)
my_matrix
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
# Note: byrow = FALSE is the default
my_matrix2 <- matrix(1:12, nrow = 3, ncol = 4)
my_matrix2
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12

Stacking Columns or Rows Using cbind() and rbind()

# Another approach  
A <- cbind(1:3, 4:6, 7:9, 10:12)
A
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
B <- rbind(letters[1:4], letters[5:8], letters[9:12])
B
##      [,1] [,2] [,3] [,4]
## [1,] "a"  "b"  "c"  "d" 
## [2,] "e"  "f"  "g"  "h" 
## [3,] "i"  "j"  "k"  "l"

Naming Rows and Columns

names(A)
## NULL
rownames(A) <- c("row1", "row2", "row3")
A
##      [,1] [,2] [,3] [,4]
## row1    1    4    7   10
## row2    2    5    8   11
## row3    3    6    9   12
colnames(A) <- c("col1", "col2", "col3", "col4")
A
##      col1 col2 col3 col4
## row1    1    4    7   10
## row2    2    5    8   11
## row3    3    6    9   12

Extracting Matrix Values by Index

A
##      col1 col2 col3 col4
## row1    1    4    7   10
## row2    2    5    8   11
## row3    3    6    9   12
dim(A)
## [1] 3 4
A[1:2, 3:4]
##      col3 col4
## row1    7   10
## row2    8   11
A[2, 4]
## [1] 11

Matrix Arithmetic

# 
Ar <- matrix(12:1, ncol=4)
Ar
##      [,1] [,2] [,3] [,4]
## [1,]   12    9    6    3
## [2,]   11    8    5    2
## [3,]   10    7    4    1
A + Ar
##      col1 col2 col3 col4
## row1   13   13   13   13
## row2   13   13   13   13
## row3   13   13   13   13

Matrix/Vector Arithmetic

A
##      col1 col2 col3 col4
## row1    1    4    7   10
## row2    2    5    8   11
## row3    3    6    9   12
A + 1:3
##      col1 col2 col3 col4
## row1    2    5    8   11
## row2    4    7   10   13
## row3    6    9   12   15

Matrix/Vector Arithmetic

# Vectors are expanded by column to a conforming matrix
A
##      col1 col2 col3 col4
## row1    1    4    7   10
## row2    2    5    8   11
## row3    3    6    9   12
A + 1:4
##      col1 col2 col3 col4
## row1    2    8   10   12
## row2    4    6   12   14
## row3    6    8   10   16

Matrix Multiply (Linear Algebra)

C <- matrix(1:4, nrow=2, ncol=2)
C
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
D <- matrix(6:1, nrow=2, ncol=3)
D
##      [,1] [,2] [,3]
## [1,]    6    4    2
## [2,]    5    3    1
C %*% D # Matrix can be multiplied using the command %*%
##      [,1] [,2] [,3]
## [1,]   21   13    5
## [2,]   32   20    8

Matrix Vector Multiply (Linear Algebra)

C <- matrix(1:4, nrow=2, ncol=2)
C
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
d <- c(2, 3)
d
## [1] 2 3
C %*% d
##      [,1]
## [1,]   11
## [2,]   16

Inverting a Square Matrix

G <- matrix(1:4, ncol=2)
G
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
solve(G)
##      [,1] [,2]
## [1,]   -2  1.5
## [2,]    1 -0.5

Inverting a Square Matrix

# Determinent `det()`
det(G)
## [1] -2
# Matrix Diagonal `diag()`
diag(G)
## [1] 1 4
# Verifying answer 
solve(G) %*% G
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1

A note on diag()

diag(c(1, 2, 3))
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    2    0
## [3,]    0    0    3
diag(3)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1

How to modify a matrix in R?

x <- matrix(1:9, nrow=3, ncol=3, byrow=F)
x
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
# Replace x[2,2] by 10 
x[2,2] <- 10
x
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2   10    8
## [3,]    3    6    9

How to modify a matrix in R?

x <- matrix(1:9, nrow=3, ncol=3, byrow=F)
x
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
# Modify elements less than 5
x[x<5] <- 0
x
##      [,1] [,2] [,3]
## [1,]    0    0    7
## [2,]    0    5    8
## [3,]    0    6    9

Transpose a Matrix

x <- matrix(1:9, nrow=3, ncol=3, byrow=F)
x
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
t(x)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9

Filling in a Matrix

my_results <- matrix(NA, nrow = 3, ncol = 3)
my_results
##      [,1] [,2] [,3]
## [1,]   NA   NA   NA
## [2,]   NA   NA   NA
## [3,]   NA   NA   NA

Filling in a Matrix

my_results[2, ] <- c(2, 4, 3)
my_results
##      [,1] [,2] [,3]
## [1,]   NA   NA   NA
## [2,]    2    4    3
## [3,]   NA   NA   NA

Filling in a Matrix

my_results[c(1, 3), ] <- 7
my_results
##      [,1] [,2] [,3]
## [1,]    7    7    7
## [2,]    2    4    3
## [3,]    7    7    7

Filling in a Matrix

my_results[c(1, 2, 3), ] <- 7
my_results
##      [,1] [,2] [,3]
## [1,]    7    7    7
## [2,]    7    7    7
## [3,]    7    7    7

Filling in a Matrix

my_results[1:3, ] <- 7
my_results
##      [,1] [,2] [,3]
## [1,]    7    7    7
## [2,]    7    7    7
## [3,]    7    7    7

Matrix Entry Types

rbind(c(1, 2, 3), c("a", "b", "c"))
##      [,1] [,2] [,3]
## [1,] "1"  "2"  "3" 
## [2,] "a"  "b"  "c"

Common Matrix Operations in R

# Division
M1<- matrix(1:15,nrow=5)

M2<- matrix(2:16,nrow=5)
M1/M2
##           [,1]      [,2]      [,3]
## [1,] 0.5000000 0.8571429 0.9166667
## [2,] 0.6666667 0.8750000 0.9230769
## [3,] 0.7500000 0.8888889 0.9285714
## [4,] 0.8000000 0.9000000 0.9333333
## [5,] 0.8333333 0.9090909 0.9375000

Common Matrix Operations in R

# Sum of rows in Matrix
rowSums(M1)
## [1] 18 21 24 27 30
# Sum of columns in Matrix
colSums(M1)
## [1] 15 40 65
# Mean of rows in Matrix
rowMeans(M1)
## [1]  6  7  8  9 10

Tables in R Markdown

mat <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
mat
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
my_tab <- data.frame(mat)
kable_styling(kable(mat))
1 2 3
4 5 6

What happened with the row and column names?

Part 5: Packages

What is an R package?

Where are packages?

How do I install packages?

If a package is available on CRAN, like most packages we will use for this course, you can install it using install.packages():

install.packages("PACKAGE_NAME_IN_QUOTES")

How do I use a package?

After a package is installed, you can load it into your current R session using library():

library(PACKAGE_NAME)
# or 
library("PACKAGE_NAME")

Note that unlike install.packages(), you do not need to include the package name in quotes.

How do I use a package?

Part 6: Data

Tibbles

Tibbles

library(tibble)
my_data <- data.frame("var1" = 1:3,
                      "var2" = c("a", "b", "c"),
                      "var3" = c(TRUE, FALSE, TRUE))
rownames(my_data) <- c("obs1", "obs2", "obs3")
my_data
##      var1 var2  var3
## obs1    1    a  TRUE
## obs2    2    b FALSE
## obs3    3    c  TRUE
my_tibble <- as_tibble(my_data, rownames = "Observation")
my_tibble
## # A tibble: 3 × 4
##   Observation  var1 var2  var3 
##   <chr>       <int> <chr> <lgl>
## 1 obs1            1 a     TRUE 
## 2 obs2            2 b     FALSE
## 3 obs3            3 c     TRUE

Tibbles

library(tibble)
my_data <- data.frame("var1" = 1:3,
                      "var2" = c("a", "b", "c"),
                      "var3" = c(TRUE, FALSE, TRUE))
rownames(my_data) <- c("obs1", "obs2", "obs3")
my_data
##      var1 var2  var3
## obs1    1    a  TRUE
## obs2    2    b FALSE
## obs3    3    c  TRUE
my_tibble <- as_tibble(my_data)
my_tibble
## # A tibble: 3 × 3
##    var1 var2  var3 
##   <int> <chr> <lgl>
## 1     1 a     TRUE 
## 2     2 b     FALSE
## 3     3 c     TRUE

Tidy Data Principles

There are three rules required for data to be considered tidy

Tidy Data Principles (Cont’d)

library(kableExtra)
untidy_dat <- data.frame("Hospital" = c("A", "B", "C", "D"),
                         "Diseased" = c(10, 15, 12, 5),
                         "Healthy"  = c(14, 18, 13, 16))
kable_styling(kable(untidy_dat))
Hospital Diseased Healthy
A 10 14
B 15 18
C 12 13
D 5 16

Tidy Data Principles (Cont’d)

library(kableExtra)
untidy_dat <- data.frame("Hospital" = c("A", "B", "C", "D"),
                         "Diseased" = c(10, 15, 12, 5),
                         "Healthy"  = c(14, 18, 13, 16))
kable_styling(kable(untidy_dat))
Hospital Diseased Healthy
A 10 14
B 15 18
C 12 13
D 5 16

Problem: column headers are values, not variables!

Tidy Data Principles (Cont’d)

tidy_dat <- data.frame("Hospital" = rep(c("A", "B", "C", "D"), each = 2),
                       "Status"   = rep(c("Diseased", "Healthy"), 4),
                       "Count"    = c(10, 14, 15, 18, 12, 13, 5, 16))
kable_styling(kable(tidy_dat))
Hospital Status Count
A Diseased 10
A Healthy 14
B Diseased 15
B Healthy 18
C Diseased 12
C Healthy 13
D Diseased 5
D Healthy 16

Another example

untidy_dat2 <- data.frame("Country" = c("A", "B"),
                          "Year"  = rep(2018, 2),
                          "m1624" = c(49, 34),
                          "m2534" = c(55, 33),
                          "f1624" = c(47, 50),
                          "f2534" = c(41, 43))
untidy_dat2
##   Country Year m1624 m2534 f1624 f2534
## 1       A 2018    49    55    47    41
## 2       B 2018    34    33    50    43

Another example (Cont’d)

untidy_dat2 <- data.frame("Country" = c("A", "B"),
                          "Year"  = rep(2018, 2),
                          "m1624" = c(49, 34),
                          "m2534" = c(55, 33),
                          "f1624" = c(47, 50),
                          "f2534" = c(41, 43))
kable_styling(kable(untidy_dat2))
Country Year m1624 m2534 f1624 f2534
A 2018 49 55 47 41
B 2018 34 33 50 43

Another example (Cont’d)

untidy_dat2 <- data.frame("Country" = c("A", "B"),
                          "Year"  = rep(2018, 2),
                          "m1624" = c(49, 34),
                          "m2534" = c(55, 33),
                          "f1624" = c(47, 50),
                          "f2534" = c(41, 43))
kable_styling(kable(untidy_dat2))
Country Year m1624 m2534 f1624 f2534
A 2018 49 55 47 41
B 2018 34 33 50 43

Another example (Cont’d)

tidy_dat2 <- data.frame("Country"   = rep(c("A", "B"), each = 4),
                        "Year"      = rep(2018, 8),
                        "Gender"    = rep(c("m", "m", "f", "f"), 2),
                        "Age_Group" = rep(c("16-24", "25-34"), 4),
                        "Counts"    = c(49, 55, 47, 41, 34, 33, 50, 43))
kable_styling(kable(tidy_dat2))
Country Year Gender Age_Group Counts
A 2018 m 16-24 49
A 2018 m 25-34 55
A 2018 f 16-24 47
A 2018 f 25-34 41
B 2018 m 16-24 34
B 2018 m 25-34 33
B 2018 f 16-24 50
B 2018 f 25-34 43

How to tidy data?

Why tidy data?

Using R to tidy data

library(dplyr)
## Warning: package 'dplyr' was built under R version 4.2.2
library(tidyr)
data("relig_income")
relig_income
## # A tibble: 18 × 11
##    religion      `<$10k` $10-2…¹ $20-3…² $30-4…³ $40-5…⁴ $50-7…⁵ $75-1…⁶ $100-…⁷
##    <chr>           <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
##  1 Agnostic           27      34      60      81      76     137     122     109
##  2 Atheist            12      27      37      52      35      70      73      59
##  3 Buddhist           27      21      30      34      33      58      62      39
##  4 Catholic          418     617     732     670     638    1116     949     792
##  5 Don’t know/r…      15      14      15      11      10      35      21      17
##  6 Evangelical …     575     869    1064     982     881    1486     949     723
##  7 Hindu               1       9       7       9      11      34      47      48
##  8 Historically…     228     244     236     238     197     223     131      81
##  9 Jehovah's Wi…      20      27      24      24      21      30      15      11
## 10 Jewish             19      19      25      25      30      95      69      87
## 11 Mainline Prot     289     495     619     655     651    1107     939     753
## 12 Mormon             29      40      48      51      56     112      85      49
## 13 Muslim              6       7       9      10       9      23      16       8
## 14 Orthodox           13      17      23      32      32      47      38      42
## 15 Other Christ…       9       7      11      13      13      14      18      14
## 16 Other Faiths       20      33      40      46      49      63      46      40
## 17 Other World …       5       2       3       4       2       7       3       4
## 18 Unaffiliated      217     299     374     365     341     528     407     321
## # … with 2 more variables: `>150k` <dbl>, `Don't know/refused` <dbl>, and
## #   abbreviated variable names ¹​`$10-20k`, ²​`$20-30k`, ³​`$30-40k`, ⁴​`$40-50k`,
## #   ⁵​`$50-75k`, ⁶​`$75-100k`, ⁷​`$100-150k`

Using R to tidy data

pivot_longer(relig_income, cols = -religion, names_to = "income", values_to = "frequency")
## # A tibble: 180 × 3
##    religion income             frequency
##    <chr>    <chr>                  <dbl>
##  1 Agnostic <$10k                     27
##  2 Agnostic $10-20k                   34
##  3 Agnostic $20-30k                   60
##  4 Agnostic $30-40k                   81
##  5 Agnostic $40-50k                   76
##  6 Agnostic $50-75k                  137
##  7 Agnostic $75-100k                 122
##  8 Agnostic $100-150k                109
##  9 Agnostic >150k                     84
## 10 Agnostic Don't know/refused        96
## # … with 170 more rows

A final reference

Part 7: Managing Data

Working Directory

getwd()
## [1] "C:/Users/princ/OneDrive - University of Connecticut/Desktop/R Markdown/STAT 302 Spring 2023/Introduction to RMarkdown and R Programming"

This location is where R will look by default!

Changing your working directory

You can change your working directory using setwd().

setwd("/Users/Prince/Documents")

You can use the shorthand .. to reference a parent directory relative to where you are now.

getwd()
## [1] "C:/Users/princ/OneDrive - University of Connecticut/Desktop/R Markdown/STAT 302 Spring 2023/Introduction to RMarkdown and R Programming"
setwd("..")
getwd()
## [1] "C:/Users/princ/OneDrive - University of Connecticut/Desktop/R Markdown/STAT 302 Spring 2023"

Working directories and R Markdown

Saving Data

You can save single R objects as .rds files using saveRDS(), multiple R objects as .RData or .rda files using save(), and your entire workspace as .RData using save.image().

object1 <- 1:5
object2 <- c("a", "b", "c")
# save only object1
saveRDS(object1, file = "object1_only.rds")
# save object1 and object2
save(object1, object2, file = "both_objects.RData")
# save my entire workspace
save.image(file = "entire_workspace.RData")

Loading Data

You can load .rds files using readRDS() and .Rdata and .rda files using load().

# load only object1
readRDS("object1_only.rds")
# load object1 and object2
load("both_objects.RData")
# load my entire workspace
load("entire_workspace.RData")

Notes on Saving and Loading R Data

The values in quotes are all filepaths, and by default, R will search for these objects in your current working directory.

You can change where R searches for images by adjusting this filepath. For example, if you save your data in a Data subfolder within your working directory, you might try

load("./Data/my_data.RData")

Other types of data

Often, you will read and write files as comma separated values, or .csv. You can do this by navigating File > Import Dataset in the menu bar, but generally I recommend doing it manually using the readr package. You will need to do so if loading data is part of your work flow, such as if it is required for an R Markdown writeup.

library(readr)
# read a .csv file in a "Data" subfolder
read_csv("./Data/file.csv")
# save a .csv file in a "Data" subfolder
write_csv("./Data/data_output.csv")

Working Directories Summary

Projects

Good file organization requires you to keep all your input data, R scripts, output data and results, and figures together. You can do this using Projects.

You can create a project by going to File > New Project. If you want your project in a folder you have already created, select Existing Directory. If you want RStudio to automatically make you a new folder with a project, select New Directory.

Then select Empty Project to create a standard project. This will create a .Rproj file on your computer.

When working with a project, save and manage your work as usual. When you close and re-open R, do so by double-clicking on your .Rproj file! This will automatically open everything as you left it, except your environment will be fresh, helping with reproducibility.

Benefits of Projects

Part 8: R Coding Style Guide

Who are you to tell me how to type?

Object Names

Use either underscores (_) or big camel case (BigCamelCase) to separate words within an object name. Do not use dots . to separate words in R functions!

# Good
day_one
day_1
DayOne

# Bad
dayone

Object Names

Names should be concise, meaningful, and (generally) nouns.

# Good
day_one

# Bad
first_day_of_the_month
djm1

Object Names

It is very important that object names do not write over common functions!

# Very  bad
t <- 23
T <- FALSE
mean <- "something"

Note: T and F are R shorthand for TRUE and FALSE, respectively. In general, spell them out to be as clear as possible.

Spacing

# Good
x[, 1]

# Bad
x[,1]
x[ ,1]
x[ , 1]

Spacing

# Good
mean(x, na.rm = TRUE)

# Bad
mean (x, na.rm = TRUE)
mean( x, na.rm = TRUE )

Spacing with Operators

# Good
height <- (feet * 12) + inches
mean(x, na.rm = 10)

# Bad
height<-feet*12+inches
mean(x, na.rm=10)

There are some exceptions we will learn more about later, such as the power symbol ^. See the Tidyverse Style Guide for more details!

Extra Spacing

# Good
list(
  total = a + b + c,
  mean  = (a + b + c) / n
)

# Also fine
list(
  total = a + b + c,
  mean = (a + b + c) / n
)

Assignment

# Good
x <- 5

# Bad
x = 5

Semicolons

# Bad
a <- 2; b <- 3

# Also bad
a <- 2;
b <- 3;

# Good
a <- 2
b <- 3

Long Lines of Code

# Good
do_something_very_complicated(
  something = "that",
  requires = many,
  arguments = "some of which may be long"
)

# Bad
do_something_very_complicated("that", requires, many, arguments,
                              "some of which may be long"
                              )