Exercise: apply and function

Exercise 1

Use apply() to calculate the total precipitation per location

rainfall <- matrix(
  sample(50:200, 25, replace = TRUE), 
  nrow = 5,
  dimnames = list(
    c("Berlin", "Hamburg", "München", "Köln", "Frankfurt")
  )
)

Exercise 2

Use sapply to find the height of the tallest tree in each plot

tree_heights <- list(
  Plot_A = c(15, 22, 19, 30),
  Plot_B = c(10, 14, 25, 18),
  Plot_C = c(5, 12, 15, 20)
)

Exercise 3

Use tapply to calculate the average bird count per habitat

bird_counts <- c(10, 20, 15, 50, 25, 30, 40, 45, 35, 60)
habitats <- c("Forest", "Forest", "Forest", "Wetland", "Wetland", 
              "Grassland", "Grassland", "Grassland", "Forest", "Wetland")

Exercise 4

Create a list of data frames:

df1 <- data.frame(X = c(1, 2, 3, 4, 5), Y = c(10, 12, 8, 15, 20))
df2 <- data.frame(X = c(2, 3, 4, 5, 6), Y = c(5, 8, 10, 12, 15))
df3 <- data.frame(X = c(3, 4, 5, 6, 7), Y = c(8, 10, 12, 15, 18))

Name the elements “df1”, “df2” and “df3”

Calculate the mean of Y of each data frame using lapply

Exercise 5

Now, create a function “niceplot” that attractively plots Y against X as a point plot and execute this function using lapply to plot all three dataframes at once. This function should also automatically change the plot title. Add an option which allows you to colour points red if they are larger than a value of choice, though the default should be 10.

Updated: