25.4 Writing a vector function

(a - min(a, na.rm = TRUE)) / (max(a, na.rm = TRUE) - min(a, na.rm = TRUE))
(b - min(b, na.rm = TRUE)) / (max(b, na.rm = TRUE) - min(b, na.rm = TRUE))
(c - min(c, na.rm = TRUE)) / (max(c, na.rm = TRUE) - min(c, na.rm = TRUE))
(d - min(d, na.rm = TRUE)) / (max(d, na.rm = TRUE) - min(d, na.rm = TRUE))  

To make this a bit clearer we can replace the bit that varies with █:

(█ - min(█, na.rm = TRUE)) / (max(█, na.rm = TRUE) - min(█, na.rm = TRUE))

To turn this into a function you need three things:

  • A name. Here we’ll use rescale01 because this function rescales a vector to lie between 0 and 1.

  • The arguments. We have just one argument that we’ll call x because this is the conventional name for a numeric vector.

  • The body. The body is the code that’s repeated across all the calls.