05_Functions.Rmd
sum(1:5)
works internally?
function_name <- function(inputs) {
output_value <- do_something(inputs)
return(output_value)
}
calc_shrub_vol <- function(length, width, height) {
volume <- length * width * height
return(volume)
}
calc_shrub_vol(0.8, 1.6, 2.0)
shrub_vol <- calc_shrub_vol(0.8, 1.6, 2.0)
shrub_vol
> width
Error: object 'width' not found
Type the name of a function that we have already used in class to view the source code of the function. Can you tell what the expected inputs and outputs of the function are?
calc_shrub_vol <- function(length = 1, width = 1, height = 1) {
volume <- length * width * height
return(volume)
}
calc_shrub_vol()
calc_shrub_vol(width = 2)
calc_shrub_vol(0.8, 1.6, 2.0)
calc_shrub_vol(height = 2.0, length = 0.8, width = 1.6)
calc_shrub_vol(height = 2.0, length = 0.8, width = 1.6)
Or
calc_shrub_vol(2.0, 0.8, 1.6)
height
, second value is
length
…Each function should be single conceptual chunk of code
Functions can be combined to do larger tasks in two ways
Calling multiple functions in a row
est_shrub_mass <- function(volume){
mass <- 2.65 * volume^0.9
}
shrub_mass <- est_shrub_mass(calc_shrub_vol(0.8, 1.6, 2.0))
library(dplyr)
shrub_mass <- calc_shrub_vol(0.8, 1.6, 2.0) %>%
est_shrub_mass()
est_shrub_mass_dim <- function(length, width, height){
volume = calc_shrub_vol(length, width, height)
mass <- est_shrub_mass(volume)
return(mass)
}
est_shrub_mass_dim(0.8, 1.6, 2.0)
We ran into some trouble Tuesday. I had defined each of my functions a couple times. And in so doing, I ended up with extra arguments to some functions and none to others.
calc_vol <- function(len = 1, width = 10, height = 1){
volume <- len * width * height
return(volume)
}
calc_mass <- function(vol){
mass <- 2.65 * vol^.9
return(mass)
}
calc_den <- function(len, width, height){
vol <- calc_vol(len, width, height)
mass <- calc_mass(len)
density <- mass/vol
return(density)
}
calc_den(len = 2, width = 3, height = 4 )
## [1] 0.2060448
calc_density <- function(length, width, height){
volume <- calc_vol(length, width, height)
mass <- calc_mass(volume)
density <- mass/volume
if (density < volume){
return(density)
} else {
print("Density impossibly large! Check your math.")
}
}
calc_density <- function(length, width, height){
volume <- calc_vol(length, width, height)
mass <- calc_mass(volume)
density <- mass/volume
density <- round(density, 3)
if (is.double(density)){
return(density)
} else {
print("Density impossibly large! Check your math.")
}
}
data_cleaning <- function(filepath){
data_raw <- read_csv(filepath)
data_clean <- data_raw %>%
drop_na()
if (sum(is.na(d_c)) == 0){
return(data_clean)
} else {
print("NAs still present!")
}
}