⌘+C
<- function(temp_f) {
fahrenheit_to_celsius return((temp_f - 32) * 5 / 9)
}fahrenheit_to_celsius(temp_f = 98.6)
Jihong Zhang*, Ph.D
Educational Statistics and Research Methods (ESRM) Program*
University of Arkansas
August 18, 2025
fahrenheit_to_celsius
that converts a temperature from Fahrenheit to Celsius.circle_area
that calculates the area of a circle given its radius.pi
in R and test the function with r = 5.standardized()
to avoid code repetition.greet
that takes two arguments, name
(default = “World”) and punctuation
(default = “!”). The function should return a greeting message.greet("Alice", "?")
should return "Hello, Alice?"
.sum()
function by passing named arguments (x = 3, y = 5
) and explain how the function handles them.result
accessible outside the function.multiply_all()
that accepts a variable number of arguments and multiplies all the numbers together. Test your function with multiply_all(2, 3, 4)
.mean()
function by using the help page. Explain why it can accept additional arguments like y
in the code below:Write a function rect_prism_volume()
that calculates the volume of a rectangular prism given its length, width, and height. Inside this function, create another function rect_area()
to calculate the base area.
The formula for the volume of a rectangular prism is:
V = A_b \times h
A_b = l \times w
where:
V = Volume of the rectangular prism,
A_b = base area
l = Length,
w = Width,
h = Height.
rescale()
that rescales a numeric vector to the range 0 to 1.rescale()
function to rescale the columns of the following data frame:---
title: "Exercise 03: R Functions"
subtitle: ""
author: "Jihong Zhang*, Ph.D"
institute: |
Educational Statistics and Research Methods (ESRM) Program*
University of Arkansas
date: "2025-08-18"
sidebar: false
execute:
warning: false
message: false
eval: false
echo: true
format:
html:
page-layout: full
toc: true
toc-depth: 2
lightbox: true
code-fold: show
---
## Creating Custom Functions
1. Write a function called `fahrenheit_to_celsius` that converts a temperature from Fahrenheit to Celsius.
- Formula: $C = \frac{(F - 32) \times 5}{9}$
- Test your function with $F = 98.6$.
```{r}
fahrenheit_to_celsius <- function(temp_f) {
return((temp_f - 32) * 5 / 9)
}
fahrenheit_to_celsius(temp_f = 98.6)
```
2. Create a function called `circle_area` that calculates the area of a circle given its radius.
- Formula: $A = \pi \times r^2$
- Use the built-in constant `pi` in R and test the function with $r = 5$.
```{r}
# r is the circle radius
circle_area <- function(r){
return(pi * r^2)
}
circle_area(r = 5)
circle_area(5) # 5 assign to r
```
------------------------------------------------------------------------
## Piping
1. Transform the following code into a pipe-based version:
```{r}
result <- filter(mtcars, hp > 100)
result <- arrange(result, desc(mpg))
result <- select(result, hp, mpg)
result
```
```{r}
mtcars |>
filter(hp > 100) |>
arrange(desc(mpg)) |>
select(hp, mpg)
```
------------------------------------------------------------------------
## Debugging Functions
1. Identify and correct the mistake in the following code:
```{r}
df |> mutate(
a = (a - mean(a, na.rm = TRUE)) / sd(a),
b = (b - mean(a, na.rm = TRUE)) / sd(b) # a should be changed to b
)
```
2. Rewrite the code by creating a custom function `standardized()` to avoid code repetition.
```{r}
standardized <- function(x){
return((x - mean(x, na.rm = TRUE)) / sd(x))
}
df |> mutate(
a = standardized(a),
b = standardized(b)
)
```
------------------------------------------------------------------------
## Arguments in Functions
1. Create a function `greet` that takes two arguments, `name` (default = "World") and `punctuation` (default = "!"). The function should return a greeting message.
- Example: `greet("Alice", "?")` should return `"Hello, Alice?"`.
```{r}
greet <- function(name = "World", punctuation = "!") {
paste0("Hello, ", name, punctuation)
}
greet(name = "Alice", punctuation = "?")
```
2. Test the `sum()` function by passing named arguments (`x = 3, y = 5`) and explain how the function handles them.
```{r}
sum(x = 3, y = 5)
sum(3, 5)
sum(c(3, 5))
# mean(x = 3, 5)
# mean(c(3, 5))
```
------------------------------------------------------------------------
## Function Scope
1. Explain why the following code throws an error:
```{r}
add <- function(x, y) {
result <- x + y # beacuase result is in the local scope
return(result)
}
add(5, 3)
result # Error
```
2. Modify the code to make the variable `result` accessible outside the function.
```{r}
add <- function(x, y) {
result <<- x + y # beacuase result is in the local scope
return(result)
}
add(6, 3)
result
```
------------------------------------------------------------------------
## Flexible Arguments
1. Write a function `multiply_all()` that accepts a variable number of arguments and multiplies all the numbers together. Test your function with `multiply_all(2, 3, 4)`.
```{r}
multiply_all <- function(x, y, z) { # flexible arguments
x * y * z
}
multiply_all(2, 3, 4)
```
```{r}
multiply_all_flexible <- function(...) {
prod(c(...))
}
multiply_all_flexible(1, 2, 3)
multiply_all_flexible(1, 2, 3, 5)
multiply_all_flexible(1, 2, 3, 5, 8)
multiply_all_flexible(c(1, 2, 3, 5, 8))
```
1. Investigate the `mean()` function by using the help page. Explain why it can accept additional arguments like `y` in the code below:
```{r}
mean(x = c(1, 2, 3), y = 3) # because y is flexible argument. It is not included into calculation of mean
```
------------------------------------------------------------------------
## Nested Functions
1. Write a function `rect_prism_volume()` that calculates the volume of a rectangular prism given its length, width, and height. Inside this function, create another function `rect_area()` to calculate the base area.
- The **formula for the volume of a rectangular prism** is:
$V = A_b \times h$
$A_b = l \times w$
where:
- V = Volume of the rectangular prism,
- $A_b$ = base area
- l = Length,
- w = Width,
- h = Height.
```{r}
# the first function
rect_area <- function(l, w){
A_base = l * w
return(A_base)
}
# the second function that contains the first function
rect_prism_volume <- function(l, w, h){
return(rect_area(l, w) * h)
}
```
1. Test your function with length = 5, width = 3, height = 4.
```{r}
rect_prism_volume(l =5, w = 3, h = 4)
```
------------------------------------------------------------------------
## Rescale Function
1. Create a custom function `rescale()` that rescales a numeric vector to the range 0 to 1.
- Formula: $x_{\text{scaled}} = \frac{x - \min(x)}{\max(x) - \min(x)}$
```{r}
rescale <- function(x){
res = (x - min(x)) / (max(x) - min(x))
return(res)
}
```
2. Use your `rescale()` function to rescale the columns of the following data frame:
```{r}
set.seed(1234)
df <- tibble(
a = rnorm(5),
b = rnorm(5),
c = rnorm(5)
)
df
```
```{r}
df |>
mutate(
a = rescale(a),
b = rescale(b),
c = rescale(c)
)
```