Make a DF with 4 columns of random numbers.
Standardize EACH variable relative to it’s minimum and maximum, after subtracting the minimum.
df <- tibble::tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
df$a <- (df$a - min(df$a, na.rm = TRUE)) /
(max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$b <- (df$b - min(df$b, na.rm = TRUE)) /
(max(df$b, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$c <- (df$c - min(df$c, na.rm = TRUE)) /
(max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
df$d <- (df$d - min(df$d, na.rm = TRUE)) /
(max(df$d, na.rm = TRUE) - min(df$d, na.rm = TRUE))
Copy-pasting is error prone
Repeated code can get long
Not scalable
You were doing 4 things in each line of code! Unreadable?
Intro to Functions
Let’s Write Some Functions!
More than One Argument
How to Build a Function
“You should consider writing a function whenever you’ve copied
and pasted a block of code more than twice”
- H. Wickham
df <- tibble::tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
df$a <- (df$a - min(df$a, na.rm = TRUE)) /
(max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$b <- (df$b - min(df$b, na.rm = TRUE)) /
(max(df$b, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$c <- (df$c - min(df$c, na.rm = TRUE)) /
(max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
df$d <- (df$d - min(df$d, na.rm = TRUE)) /
(max(df$d, na.rm = TRUE) - min(df$d, na.rm = TRUE))
[1] 4
Intro to Functions
Let’s Write Some Functions!
More than One Argument
How to Build a Function
[1] 4
Should return 4
max_minus_min <- _______(___){
ret_value <- ___(___) - ___(___)
___(___)
}
max_minus_min(c(4,7,1,6,8))
[1] 7
Intro to Functions
Let’s Write Some Functions!
More than One Argument
How to Build a Function
Functions can take many arguments:
These can be of any object type
[1] 3
make_mean <- function(a_vector, ...){
sum_vector <- sum(a_vector, ...)
n <- length(a_vector)
return(sum_vector/n)
}
make_mean(c(4,5,6), na.rm=TRUE)
[1] 5
Write a function and paste it into the etherpad that
c(4,5,6)
to test (= 77)paste()
.
Intro to Functions
Let’s Write Some Functions!
More than One Argument
How to Build a Function
OK, what’s normally going to change
AND - what could change under some circumstances?
Write some test code (START WITH COMMENTS!)
“You should consider writing a function whenever you’ve copied
and pasted a block of code more than twice”
- H. Wickham