Practicing with Custom Functions Answer Key

Authors

Mary Piper

Meeta Mistry

Radhika Khetani

Will Gammerdinger

Published

September 5, 2025

Exercises

  1. Custom Functions - Let’s create a function temp_conv(), which converts the temperature in Fahrenheit (input) to the temperature in Kelvin (output). Let’s perform a two-step calculation: first convert from Fahrenheit to Celsius, and then convert from Celsius to Kelvin.

    • The formula for celsius to farenheight: temp_c = (temp_f - 32) * 5 / 9
    • The formula for celsius to kelvin: temp_k = temp_c + 273.15
    • Test your function. If your input is 70, the result of temp_conv(70) should be 294.2611.
# Create temp_conv_function
temp_conv <- function(temp_f) {
  temp_c = (temp_f - 32) * 5 / 9
  temp_k = temp_c + 273.15
  return (temp_k)
}
  1. Nesting Functions - Now we want to round the temperature in Kelvin (output of temp_conv()) to a single decimal place.

    • Use the round() function with the newly-created temp_conv() function to achieve this in one line of code.
    • If your input is 70, the output should now be 294.3.
# Round output of temp_conv to 1 digit
round(temp_conv(70), digits = 1)
[1] 294.3