# welcome to week 10, our last week together! # intro to writing functions my_sum <- function(a, b){ the_sum <- a + b return(the_sum) } the_sum_2 <- 10 + 4 # this object will appear in the global environment my_sum(a = 5, b = 10) # the object my_sum is self-contained within this function a <- 20 b <- 2 my_sum() # my_sum can't find a and b from the global environment, you need to give them as arguments my_sum(10, 35) my_sum2 <- function(a = 2, b = 5){ the_sum <- a + b return(the_sum) } my_sum2() my_sum2(12) my_sum2(b = 25) my_sum2(4, 1) # functions to convert temperatures F_to_K <- function(temp){ K <- ((temp - 32) * (5/9)) + 273.15 return(K) } # source()-ing functions source("code/functions.R") F_to_K(32) F_to_K(212) library(tidyverse) d <- read_csv("data/gapminder.csv") d # making a function that returns a line plot of pop over time for a single country d %>% filter(country == "Afghanistan") %>% ggplot(aes(x = year, y = pop)) + geom_line() plot_pop_growth <- function(data, pcountry){ plot <- data %>% filter(country == pcountry) %>% ggplot(aes(x = year, y = pop)) + geom_line() return(plot) } plot_pop_growth(data = d, pcountry = "Bulgaria") # intro to iteration # lots of base functions are already vectorized x <- 1:10 log(x) # for loops for(i in 1:10){ print(i) } # multiple lines of code in one loop for(i in 1:10){ print(i) print(i^2) } # using i as an index to subset for(i in 1:10){ print(letters[i]) print(mtcars$mpg[i]) } for(cat in 1:10){ print(letters[cat]) print(mtcars$mpg[cat]) } # making an empty results vector and filling it in results <- rep(NA, nrow(mtcars)) for(i in seq_along(results)){ results[i] <- mtcars$wt[i] * 1000 } results gapminder <- read_csv("data/gapminder.csv") countries <- unique(gapminder$country)[1:5] for (i in seq_along(countries)) { p <- plot_pop_growth(data = gapminder, pcountry = countries[i]) + ggtitle(countries[i]) print(p) ggsave(filename = paste0("images/gg_example_", countries[i], ".jpg"), plot = p) } # conditional statements # sometimes you want to run some code, but only if a certain condition is met for(i in 1:10){ if(i < 5){ print(paste(i, "is less than 5")) } else { print(paste(i, "is greater than or equal to 5")) } } # case_when is a nested conditional mtcars %>% mutate(car_size = case_when( wt > 3.5 | cyl == 8 ~ "big", wt > 2.5 ~ "medium", TRUE ~ "small" )) if(x > 10){ } else if(x < 10){ } else if(x = 10){ } rep(5, 8) rep(NA, 12) rep(NA, nrow(mtcars)) 1:nrow(mtcars) seq_along(results) results <- NULL 1:results seq_along(results)