Presentation 1A: Intro to R

R as a calculator

Adding

1+1
[1] 2

Subtracting

2-1
[1] 1

Multiplication

3*3
[1] 9

Division

15/3
[1] 5

Exponentiation

10^2
[1] 100

Base-2 logarithm

log2(20)
[1] 4.321928

Base-10 logarithm

log10(20)
[1] 1.30103

Define variables

a <- 5

b <- 3


a + b 
[1] 8
c <- a + b


c
[1] 8

Check objects in environment

ls()
[1] "a"               "b"               "c"               "pandoc_dir"     
[5] "quarto_bin_path"

Object Types

Character

char1 <- "Hello World!"
char1
[1] "Hello World!"
class(char1)
[1] "character"

Numeric

num1 <- 5
num1
[1] 5
class(num1)
[1] "numeric"

Vector

vector1 <- c(1, 2, 3, 4, 5, 'hello', 'world', 7, 1)
vector1
[1] "1"     "2"     "3"     "4"     "5"     "hello" "world" "7"     "1"    
class(vector1)
[1] "character"

List

list1 <- list(1, 2, 3, 4, 5, 'hello', 'world', 7, 1)
list1
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

[[6]]
[1] "hello"

[[7]]
[1] "world"

[[8]]
[1] 7

[[9]]
[1] 1
class(list1)
[1] "list"

Vector of numeric

vector2 <- c(1, 2, 4, 6, 8, 2, 5, 7)
vector2
[1] 1 2 4 6 8 2 5 7

Functions

Summing a vector

?sum
sum(vector2)
[1] 35

Mean of vector

?mean
mean(vector2)
[1] 4.375
mean(vector2) # mean/average
[1] 4.375
median(vector2) # median
[1] 4.5
sd(vector2) # standard deviation
[1] 2.559994
sum(vector2) # sum
[1] 35
min(vector2) # minimum value
[1] 1
max(vector2) # maximum value
[1] 8
length(vector2) # length of vector
[1] 8

Working directory (Exclude/Move)

The term path refers to the trajectory you need to follow from the place you are β€˜located’ on your computer to the place you want to work from. When working with Quarto your working directory (wd) is always the same locations as your Quarto document (is not true for .R scripts!). The wd becomes important when we start loading data in from other places (presentation 2).

See current working directory.

getwd()
[1] "/Users/srz223/Desktop/DataLab/FromExceltoR/Teachers/Presentations"

Change working directory.

setwd("/Users/kgx936/Desktop/HeaDS/GitHub_repos/FromExceltoR")

Read excel file from path relative to working directory.

library(readxl)
read_excel("/Data/climate.xlsx")

Read excel file from absolute path.

read_excel("~/Users/kgx936/Desktop/HeaDS/GitHub_repos/FromExceltoR/Data/climate.xlsx")