functions

Chapter 25

Published

November 13, 2024

Exercise

  1. Write a function that takes three parameters (.data, columns, fn) that applies the mathematical function fn to the columns of .data indexed numerically by columns.
  1. Apply your function to two different datasets.

  2. Now make a summary function that allows for the possibility to remove NA.

  1. Perform a simple mathematical operation (e.g., add 1) to a chosen set of columns of a given dataset. (Use across with mutate)
  1. Improve your function above to allow users to input the names of the variables.
  1. Apply a user-defined (non-summary) function to a set of columns of data.
  1. Recall simple rescaling function from last week
rescale <- function(a) {
    rng <- range(a, na.rm = TRUE)
    (a - rng[1])/(rng[2] - rng[1])
}
  1. Apply it to rescale all numeric columns of a dataset. First do it with a mutate, then write a function that takes rescale as a parameter.
my_fun(diamonds,where(is.numeric),rescale)
  1. For dynamically naming column names see:

https://stackoverflow.com/questions/26003574/use-dynamic-name-for-new-column-variable-in-dplyr?rq=1

glue