Repeating Things 1 (flash cards)

Question 1

What is a vectorized function?

A function that takes a vector of values, does elementwise calculations, and returns a vector of results.

Question 2

When will a function you write automatically work on vectors?

When it only includes vectorized functions or calculations.

Question 3

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

Question 4

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)

Question 5

What type of result does each of these return?

  • map_dbl()
  • map_chr()
  • map_lgl()
  • map()
  • map_dbl() - vector of numbers
  • map_chr() - vector of character strings
  • map_lgl() - vector of logicals (i.e., TRUE or FALSE)
  • map() - a list (can contain any type)

Question 6

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)

Question 7

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)

Question 8

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))

Question 9

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))

Question 10

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))

Question 11

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.