What is a vectorized function?
A function that takes a vector of values, does elementwise calculations, and returns a vector of results.
Flip the card by pressing the q key.
When will a function you write automatically work on vectors?
When it only includes vectorized functions or calculations.
vectorized_function <- function(input_1, input_2){
output_vector <- input_1 * input_2
return(output_vector)
}
What does vectorized_function(c(1, 1, 3), c(2, 2, 3)) return?
[1] 2 2 9
How do you run non_vectorized_function() on each value in c(1, 2, 3) and get back a vector of numbers?
Use map_dbl() from the purrr package
library(purrr)
map_dbl(c(1, 2, 3), non_vectorized_function)
What type of result does each of these return?
map_dbl()map_chr()map_lgl()map()map_dbl() - vector of numbersmap_chr() - vector of character stringsmap_lgl() - vector of logicals (i.e., TRUE or FALSE)map() - a list (can contain any type)How do you run non_vectorized_function() with two arguments, with the first argument set to c(1, 2, 3) and the second argument set to c("A", "B", "A") when this will return a vector of numbers?
Use map2_dbl()
map2_dbl(c(1, 2, 3), c("A", "B", "A"), non_vectorized_function)
What map function do you use if your function has more than two arguments?
pmap()
Put the vectors in a list() in the same order as the function’s arguments
pmap_dbl(list(vector_1, vector_2, vector_3), non_vectorized_function)
How do you add a column called new_column to df by running vectorized_function() on column_1 and column_2?
df |>
mutate(new_column = vectorized_function(column_1, column_2))
How do you add a column called new_column to df by running non_vectorized_function() on column_1 and column_2?
Add rowwise() before mutate()
df |>
rowwise() |>
mutate(new_column = non_vectorized_function(column_1, column_2))
How do you get one result per group in the group_column of df by running summarizing_function() on value_column?
df |>
group_by(group_column) |>
summarize(new_column = summarizing_function(value_column))
What should a function used inside summarize() take as input and return?
It should take one or more vectors as input and return a single value.