<- 1:20 x
Homework 3
Due 2/24/24 @ 11:59 PM
Use an RMD or QMD file to create the assignment.
You must comment all your code to receive credit.
Submit the *.html file to canvas.
Problem 1
Using the vectors below, use sapply()
to determine if the numbers are even or odd.
Answer
<- function(x){
evenodd if (x %% 2 ==0){
return("Even")
else {
} return("Odd")
}
}sapply(x, evenodd)
Problem 2
Evaluate the following function:
\[ k(j(i(h(g(f(x)))))) \]
\(f(x)=\sin(x)\)
\(g(x) = x^2 +5\)
\(h(x) = \exp{2x}\)
\(i(x) = \sin(\pi x)\)
\(j(x) = x^2 + 5\)
\(k(x) = \sqrt x\)
You are not allowed to store values, but you may create and store functions.
Answer
4 |> sin() |>
^2 + 5)() |>
(\(x) xexp(2*x))() |>
(\(x) sinpi() |>
^2 + 5)() |>
(\(x) xsqrt()
Problem 3
From the penguins
data set from palmerpenguins
package, create a new variable indicating if the penguin’s flipper length (flipper_length_mm
) is greater than the average flipper length. Afterwards, group by the new variable and find the mean body_mass_g
.
Answer
library(tidyverse)
library(palmerpenguins)
|> drop_na() |>
penguins mutate(hilo = ifelse(flipper_length_mm > mean(flipper_length_mm),
"Flipper Length greater than mean",
"Flipper Length less than mean")) |>
group_by(hilo) |>
summarise(mean = mean(body_mass_g))
Problem 4
From the penguins
data set from palmerpenguins
package, find the mean and standard deviation of flipper_length_mm
by species
.
Answer
library(tidyverse)
library(palmerpenguins)
|> drop_na() |>
penguins group_by(species) |>
summarise(mean = mean(flipper_length_mm),
sd = sd(flipper_length_mm))
Problem 5
Using the vector random_dates
generated from the code below:
# Set the start and end dates
<- as.POSIXct("2022-01-01 00:00:00")
start_date <- as.POSIXct("2022-12-31 23:59:59")
end_date
# Generate a vector of random dates and times between the start and end dates
<- as.POSIXct(runif(10, start_date, end_date), origin = "1970-01-01")
random_dates
# Print the vector of random dates and times
random_dates
Use sapply()
to determine what day of the week (in words) does the date represent. Hint: Look at the wday
function from lubridate
.
Answer
library(tidyverse)
sapply(random_dates, wday, label = TRUE)