Ben Bellman
August 29, 2018
if ()statement to run code only if a condition is metx <- 5
if (x < 10) {x + 1}
[1] 6
x <- 15
if (x < 10) {x + 1}
else functionx <- 15
if(x < 10){
x + 1
} else {
print("Statement was false")
}
[1] "Statement was false"
x <- 1
while (x < 8){
x <- x + 1
print(x)
}
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
for() functionlibrary(tidyverse)
for(year in 2010:2015){
paste("The year is", year, sep = " ") %>%
print()
}
[1] "The year is 2010"
[1] "The year is 2011"
[1] "The year is 2012"
[1] "The year is 2013"
[1] "The year is 2014"
[1] "The year is 2015"
library(here)
salaries <- read_csv(here("data","white-house-salaries.csv"))
t1 <- Sys.time()
for(a in 1:nrow(salaries)){
salaries$salary[a] / 1000
}
t2 <- Sys.time()
loop <- t2 - t1
loop
Time difference of 0.0214889 secs
dplyr functions are vectorized processesmap() from the purrr package in tidyverse vectorizes functions over lists and vectorst3 <- Sys.time()
invisible(salaries$salary / 1000) # suppress output
t4 <- Sys.time()
vect <- t4 - t3
loop
Time difference of 0.0214889 secs
vect
Time difference of 0.002082109 secs
0.01929402 / 0.003953934 # How many times longer was loop?
[1] 4.879702
function() function