class: center, middle, inverse, title-slide # Making Functions for Rtistry ### Meghan Harris, MPH ### R Ladies Johannesburg ### Tuesday, May 24th, 2022 | (24/05/2022) --- class: dark, animated, fadeIn <h1><span>Reach Out</span></h1> <div class = "contactbox"> <img class = "bio", src="images/meghanharris.jpg", style="width:300px;height:200px;"> <div class = "contact"> <br> <a href="https://twitter.com/meghansharris"><img class = "icon", src ="images/twitter.png">@meghansharris</a> <br> <a href="https://thetidytrekker.com"><img class = "icon", src = "images/web.png">TheTidyTrekker.com</a> <br> <a href="https://github.com/Meghansaha"><img class = "icon", src = "images/github.png">@meghansaha</a> <br> <a href="https://www.linkedin.com/in/meghan-harris/"><img class = "icon", src = "images/linkedin.png">meghan-harris</a> <br> <a href="mailto:meghansa@buffalo.edu"><img class = "icon", src= "images/email.png">meghansa@buffalo.edu</a> </div> </div> --- class: light, animated, fadeIn <h1><span>What Are We Doing Today?</span></h1> - What Are Functions in R? - Why Use Functions in Rtistry? - Using Base R for Data - Using Purrr for Data - Types of Functions for Rtistry - Live Coding Example --- class: dark, animated, middle, fadeIn # <center>What Are Functions in R?</center> *<center>"Work Smart, Not Hard"</center>* --- class: light, animated, fadeIn <h1><span>What Are Functions in R?</span></h1> Functions are EVERYWHERE in R and you've most likely have used some already even if you haven't made any yourself: <br> -- - Functions in R can be considered *objects* that we can use to **do something.** -- - According to the book [Advanced R](https://adv-r.hadley.nz/functions.html#function-fundamentals) by [Hadley Wickham](https://twitter.com/hadleywickham), Most functions are made up of three parts: - `formals()` - arguments that control how the function's called - `body()` - the code inside of the function - `environment()` - the structure that determines how the function finds the values associated the names in the function -- - In this presentation, we'll focus mainly on **`formals`** and the **`body`** components of custom functions that can be used in rtistry. --- class: light, animated, fadeIn <h1><span>What Are Functions in R?</span></h1> Let's look at an example of a basic function: ```r # Creating a function named "rtistry_message": rtistry_message <- function(adjective){ # Setting up our custom message: todays_message = paste("Today is a", adjective, "Day for Rtistry!") # Returning our custom message to the console: return(todays_message) } ``` -- ```r # Using our function: rtistry_message("Great") ``` ``` ## [1] "Today is a Great Day for Rtistry!" ``` -- The **`adjective`** argument is a `formal()` that will control how the function is called. **Everything** inside of the curly brackets `{ }` is the `body()` of the function. In rtistry, we can create simple or complex functions to assist in the creation of our pieces. --- class: dark, animated, middle, fadeIn # <center>Why Use Functions in Rtistry?</center> *<center>"No Really. Stop Making Things Hard"</center>* --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Build up a tool box of functionalities, especially for things you'd like to do often. -- <br><br> <center><img class = "special", src = "images/art set.jpg" width = "300px", height = "300px"></center> --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Streamline code and reduce any manual (copy and paste) work --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> <img class = "special", align = "left", src = "images/streamline1.png", height = "400px"> <img class = "special", align = "right", src = "images/streamline2.png", height = "300px"> <p align = "right"> <sub>Thank you <a href="https://twitter.com/StarTrek_Lt"> Zane(@StarTrek_Lt)</a><br>For reminding me <a href= "https://carbon.now.sh/">Carbon</a> exists<br> and for reviewing the slides 😊</sub></p> --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Streamline code and reduce any manual (copy and paste) work <img class = "special", align = "center", src = "images/rectangles.png", width = "100%", height = "380px"> --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Streamline code and reduce any manual (copy and paste) work ```r # Load in your libraries==== library(ggplot2) library(dplyr) library(purrr) #Setting seed for reproducibility==== set.seed(1129) # Set up some options==== x_transformer <- c(0,15,30) rectangle_groups <- c("left","middle","right") rectangle_colors <- c("#82954B", "#AC7D88", "#143F6B") rectangle_borders <- map_chr(rectangle_colors, ~colorRampPalette(c(.x,"#000000"))(10)[5]) # Create a "base" rectangle==== rectangle <- tibble(x = c(seq(0,10, length.out = 100), rep(10,100), seq(10,0, length.out = 100), rep(0,100)), y = c(rep(0,100), seq(0,20, length.out = 100), rep(20,100), seq(20,0, length.out = 100))) ``` --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Streamline code and reduce any manual (copy and paste) work ```r # Use Purrr functions to apply options to the base rectangle and create the data needed==== rectangles_df <- pmap_df(list(x_transformer, rectangle_groups, rectangle_colors, rectangle_borders), ~rectangle %>% mutate(x = x + ..1, group = ..2, fill = ..3, color = ..4)) # Plot the piece==== rectangles_df %>% ggplot(aes(x = x, y = y, group = group)) + theme_void()+ geom_polygon(fill = rectangles_df$fill , color = rectangles_df$color, size = 1.5, position = position_jitter(width = .05, height = .02)) + theme(plot.background = element_rect(fill = "#F1DDBF")) ``` --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Streamline code and reduce any manual (copy and paste) work <img class = "special", align = "center", src = "images/rectangles.png", width = "100%", height = "380px"> --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Make it easier to create variations in your work ```r # Load in your libraries==== library(ggplot2) library(dplyr) library(purrr) #Setting seed for reproducibility==== set.seed(1129) # Set up some options==== x_transformer <- c(0,15,30) rectange_groups <- c("right","middle","left") rectangle_colors <- c("#1C658C", "#83BD75", "#CDBE78") back_color <- "#363062" # Just wrap everything in a custom function for better readability and ease==== rectangle_maker <- function(transformer, groups, colors){...} # Use the custom function to make the data==== rectangles_df <- rectangle_maker(x_transformer, rectange_groups, rectangle_colors) ``` ??? Rectangle colors = blue, green, yellow <br> background color = purple --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Make it easier to create variations in your work ```r # Plot the piece==== rectangles_df %>% ggplot(aes(x = x, y = y, group = group)) + theme_void()+ geom_polygon(fill = rectangles_df$fill , color = rectangles_df$color, size = 1.5, position = position_jitter(width = .05, height = .02)) + theme(plot.background = element_rect(fill = back_color)) ``` ??? Using previous rectangle ex - easily change the colors <br> Background color object is put directly into the ggplot's theme function, we could put this in the function if we place the ggplot function in the "rectangle_maker" function as well --- class: light, animated, fadeIn <h1><span>Why Use Functions in Rtistry?</span></h1> - Make it easier to create variations in your work <img class = "special", align = "center", src = "images/varied_rectangles.png", width = "100%", height = "380px"> --- class: dark, animated, middle, fadeIn # <center>Using Base R for Data</center> *<center>"Just like Vanilla Ice Cream 🍦, Base R is underrated"</center>* --- class: light, animated, fadeIn <h1><span>Using Base R for Data</span></h1> We've already seen some examples of how we can create functions in R with the `function()` directive. Just like with many processes in R, you can make functions completely using Base R without any extra packages, if you're an R purist. -- - There's no limit to what functions you can use in Base R to make your data but here's a few that are in my toolbox: <br> <br> -- - <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/function"> `function()`</a> -- - <a href="https://www.rdocumentation.org/packages/memisc/versions/0.99.30.7/topics/Sapply"> `sapply()` and `lapply()`</a> -- - <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/sample"> `sample()`</a> -- - <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/rep"> `rep()`</a> -- - <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/expand.grid"> `expand.grid()`</a> -- - <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/Control">Control Flows</a> ??? Quick reference to some functions I use frequently, mentioned in First rtistry workshop, slides available in my GitHub repo for this talk --- class: dark, animated, middle, fadeIn # <center>Using Purrr for Data</center> *<center>"Sometimes I wonder why Purrr has three R's"</center>* --- class: light, animated, fadeIn <h1><span>Using Purrr for Data</span></h1> <a href="https://purrr.tidyverse.org/">Purrr</a> is a Tidyverse package that <i>"enhances R's functional programming toolkit by providing a complete and consistent set of tools for working with functions and vectors."</i> -- - The Purrr package has lot of useful functions that can help with your rtistry. Here's just a few of my most commonly used functions: <br> <br> -- - <a href="https://purrr.tidyverse.org/reference/map.html"> The `map()` Family</a> -- - <a href="https://www.rdocumentation.org/packages/memisc/versions/0.99.30.7/topics/Sapply"> The `map2()` and `pmap()` Families</a> -- - <a href="https://purrr.tidyverse.org/reference/keep.html"> `keep()` and `discard()` Functions</a> -- - <a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/rep"> `modify()` Functions</a> --- class: dark, animated, middle, fadeIn # <center>Types of Functions in Rtistry</center> *<center>"There's no rules in Rtistry. Do what you want..."</center>* --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> The longer you do rtistry you may realize that you may start to develop a certain style. You may find yourself needing to do repeated types of operations. Likewise, you may get to a point where you'll be looking for new solutions to new challenges. Your journey may lead you to creating the following types of basic functions: -- - Repetition --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> ```r #Function for repeating vertical bars=== library(tidyverse) vertical_bars <- function(n_bars, color_pal, background_color){ #Setting iterations for "n" amount of bars=== iterations = 1:n_bars #Creating a color gradient based on supplied colors values and desired "n"=== bar_colors = colorRampPalette(color_pal)(n_bars) #Creating a "base" bar to copy and repeat over=== base_bar = tibble(x = c(0,1,1,0), y = c(0,0,10,10), group = 0) #Creating all the data needed to repeat the base bar and apply the generated color palette=== bars <- map2_df(iterations, bar_colors, ~base_bar %>% mutate(x = x + 1.5*.x, group = group + .x, color = .y)) #Creating the actual ggplot=== bars %>% ggplot(aes(x,y, group = group))+ theme_void()+ geom_polygon(fill = bars$color, color = "#000000", size = 1)+ theme(plot.background = element_rect(fill = background_color))} ``` ??? For the sake of time, I won't go into this, code is available on the slides on GitHub <br> But here for any of you that want to go back and reproduce this image --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> ```r #Options for the Piece=== color_pal <- c("#363062", "#4D4C7D", "#827397", "#E9D5DA") # A purple-ish color palette back_color <- "#383838" # Some type of dark gray # Using the function vertical_bars(10, color_pal, back_color) ``` <center> <img src = "images/rep_ex.png", height = "300px", width = "100%"> </center> --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> - Randomization ```r grid_maker <- function(rows,cols){...} ``` <center> <img src = "images/rando_1.png", height = "160px"> <img src = "images/rando_2.png", height = "160px"> </center> <center> <img src = "images/rando_3.png", height = "160px"> <img src = "images/rando_4.png", height = "160px"> </center> --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> - Helpers/Plug-ins ```r # Data from another function=== squiggle_mess <- horiz_lines(0,10,15,10) # Helper function to plot the data and add variation to size and background color=== plot_helper <- function(wide_size, small_size, background_color){ # Printing the piece=== squiggle_mess %>% ggplot(aes(x,y, group = group))+ theme_void()+ geom_path(size = wide_size, color = "#000000", lineend = "round", alpha = .7)+ geom_path(size = small_size, color = "#ffffff", linetype = 2, position = position_jitter(height = .09))+ theme(plot.background = element_rect(fill = background_color))+ coord_cartesian(expand = TRUE, xlim = c(0,20)) } ``` ??? helpers/plug-ins can be used to build off of existing functions/pieces to introduce variation easily --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> - Helpers/Plug-ins ```r plot_helper(wide_size = 10, small_size = .1, background_color = "purple") ``` <center> <img src = "images/helper_1.png", height = "350px"> </center> --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> - Helpers/Plug-ins ```r plot_helper(wide_size = 20, small_size = 5, background_color = "green") ``` <center> <img src = "images/helper_2.png", height = "350px"> </center> --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> - Helpers/Plug-ins ```r plot_helper(wide_size = 2, small_size = 5, background_color = "orange") ``` <center> <img src = "images/helper_3.png", height = "350px"> </center> --- class: light, animated, fadeIn <h1><span>Types of Functions in Rtistry</span></h1> - Procedural/Algorithmic ```r # A 200-ish line function that procedurally creates circles in a "packing" fashion=== circle_packer <- function(n,min_x,max_x,min_y,max_y){...} ``` <center> <img src = "images/procedural.png", height = "300px"> </center> ??? getting more involved may lead to procedure/algorithmic when you want to start calculating things, implementing complex logic, etc. <br> still working on this so not publicly available --- class: dark, animated, middle, fadeIn # <center>Live Coding Example</center> *<center>"AKA: The part where Meghan probably forgets everything she knows because, pressure."</center>*