---
title: "Functional Programming"
output: html_document
---
```{r, include = FALSE}
library(tidyverse)
```
Check out this purrr tutorial by Jenny Bryan: https://jennybc.github.io/purrr-tutorial/ls02_map-extraction-advanced.html
Additional content to read up on:
https://jennybc.github.io/purrr-tutorial/ls01_map-name-position-shortcuts.html
0. Create a new dataset from `iris` called `iris_lab`. Use this for the lab.
```{r}
iris_lab <- iris
```
1. Working with the `iris_lab` data, use `mutate` and `across` to change the numeric variables to be rounded with the `round` function. Take a look with `head()`- do this for the rest of the questions in which you create an output of data.
```{r}
iris_lab %>%
mutate(across(.cols = !Species, round)) %>%
head()
# OR
iris_lab %>%
mutate(across(.cols = where(is.numeric), round)) %>%
head()
```
2. Now do the same thing as question one, but this time set the number of digits for rounding to be 1.
```{r}
iris_lab %>%
mutate(across(.cols = !Species, ~ round(.x, digits = 1))) %>%
head()
```
3. Create a function for adding 2 to a value and dividing by 6. Call the function `new_function` and use x as the input. Apply this function to the numeric columns of the `iris_lab` data. Hint: start with `function(x){}`. Fill in the curly brackets.
```{r}
new_function <- function(x){(x+2)/6}
iris_lab %>%
mutate(across(.cols = !Species, ~ new_function(.x))) %>%
head()
```
4. Now create a function that includes x and y inputs. Call the function `div_function` and use it to divide x by y and then add 3 to the outcome. Hint: start with `function(x, y){}`. Fill in the curly brackets.
```{r}
div_function <- function(x, y){(x/y)+ 3}
```
5. Use `if_all()` to check if there are iris flowers with sepal and petal widths and lengths (all the `iris_lab` numeric variables) greater than 2 centimeters but less than 6 centimeters (which is the unit, if you type in ?iris you can learn more about the data). Hint - use `filter`. If any are, how many?
```{r}
iris_lab %>%
filter(if_all(starts_with(c("Petal", "Sepal")), ~.x > 2 & .x < 6)) %>%
head()
```
6. the function `format()` with the argument `scientific = TRUE` can be used to format numbers in scientific notation. For example:
```{r}
format(10000, scientific = TRUE)
```
Use `modify_if` to convert *numeric* columns of `iris_lab` to be in scientific notation.
```{r}
iris_lab <- iris_lab %>%
modify_if(is.numeric, ~ format(.x, scientific = TRUE))
head(iris_lab)
```