Go back to the main page


Example Assignment R Solutions

library(knitr)
library(kableExtra)
library(pillar)

formatted_table <- function(df) {
  col_types <- sapply(df, pillar::type_sum)
  new_col_names <- paste0(names(df), "<br>", "<span style='font-weight: normal;'>", col_types, "</span>")
  kbl(df, 
      col.names = new_col_names, 
      escape = FALSE, # This is crucial to allow the <br> tag to work
      format = "html" # Ensure HTML format, although often auto-detected
      ) %>%
    kable_styling(bootstrap_options = c("striped", "hover", "responsive"))
}
library(tidyverse)

Exercise 01

The Comet Goldfish Lifespan Prediction Dataset provides a structured collection of variables used to estimate the longevity of Carassius auratus.

The fictive dataset includes several measurements: - Environmental Factors: Habitat type (e.g., lakes, ponds), water pH, and tank specifications. - Biological Metrics: Average length and weight, gender, and specimen color variations. - Target Variable: Lifespan (years). Answer the following questions:

  1. Download the data at Predict lifespan of a comet goldfish. Load the csv in RStudio.
ex1 <- read_csv("./data/exercise01/archive/fish_data.csv")
formatted_table(head(ex1))
id
dbl
average_length(inches))
dbl
average_weight(inches))
dbl
habitat
chr
ph_of_water
dbl
color
chr
Gender
lgl
life_span
dbl
1 14.69 5.87 ponds 6.2 Reddish_Orange FALSE 10.9
2 1.32 3.86 idlewater 6.8 Calico TRUE 5.2
3 14.23 12.09 lakes 7.9 Reddish_Orange TRUE 25.3
4 2.54 3.20 rivers 6.7 White FALSE 16.4
5 13.10 9.81 lakes 7.8 Orange TRUE 3.2
6 15.20 8.99 lakes 7.8 White FALSE 21.6
  1. Filter data to exclude blanks for the column Gender. Also create a new column based on the following: True should be mapped to Male, False to Female.
ex1_cleaned <- ex1 %>%
  filter(!is.na(Gender)) %>%
  mutate(Gender_Name = if_else(Gender == TRUE, "Male", "Female"))
formatted_table(head(ex1_cleaned))
id
dbl
average_length(inches))
dbl
average_weight(inches))
dbl
habitat
chr
ph_of_water
dbl
color
chr
Gender
lgl
life_span
dbl
Gender_Name
chr
1 14.69 5.87 ponds 6.2 Reddish_Orange FALSE 10.9 Female
2 1.32 3.86 idlewater 6.8 Calico TRUE 5.2 Male
3 14.23 12.09 lakes 7.9 Reddish_Orange TRUE 25.3 Male
4 2.54 3.20 rivers 6.7 White FALSE 16.4 Female
5 13.10 9.81 lakes 7.8 Orange TRUE 3.2 Male
6 15.20 8.99 lakes 7.8 White FALSE 21.6 Female
  1. Create a Pie chart to show the proportion of the different genders. You may need to use R formulas to prepare the data. Provide a logical title.
gender_counts <- ex1_cleaned %>%
count(Gender_Name)
formatted_table(gender_counts)
Gender_Name
chr
n
int
Female 1007
Male 969
p <- gender_counts %>%
  ggplot(aes(x = "", y = n, fill = Gender_Name)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0) +
  labs(title="Percentage of males and females") +
  theme_void() # remove background, grid, numeric labels
p

  1. Create a box plot to compare the life span between the habitats. Provide a logical title together with axis titles and units.
p <- ex1_cleaned %>% ggplot(aes(x = `habitat`, y = `life_span`)) + 
  geom_boxplot() +
  labs(title="Boxplot showing life span for different habitats",
       x = "Habitat Type",
       y = "Lifespan (Years)") +
  theme(axis.text.x = element_text(angle = 45, hjust=1))
p

  1. Create a barplot that shows the average lifespan for each habitat. Provide a logical title together with axis titles and units.
    Hint: you need group_by and summarise for this.
summ_data <- ex1_cleaned %>%
  group_by(habitat) %>%
  summarize(across(everything(), list(mean = mean)))
formatted_table(summ_data)
habitat
chr
id_mean
dbl
average_length(inches))_mean
dbl
average_weight(inches))_mean
dbl
ph_of_water_mean
dbl
color_mean
dbl
Gender_mean
dbl
life_span_mean
dbl
Gender_Name_mean
dbl
idlewater 1039.9368 10.38439 10.66716 6.982895 NA 0.5289474 13.84974 NA
lakes 989.5036 10.63305 10.43830 7.015108 NA 0.4964029 14.22566 NA
ponds 957.4369 10.48614 10.33396 7.033586 NA 0.4494949 14.23434 NA
rivers 1045.8900 11.20251 10.66570 7.032737 NA 0.4782609 14.80384 NA
slowmovingwaters 944.8954 10.07411 10.15046 7.008163 NA 0.5000000 14.82806 NA
p <- summ_data %>%
  ggplot(aes(x = `habitat`, y = `life_span_mean`)) +
  geom_bar(stat = "identity", position="stack") +
  labs(title="Average life span for each habitat",
       x = "Habitat Type",
       y = "Lifespan (Years)")  +
  theme(axis.text.x = element_text(angle = 45, hjust=1))
p

  1. Investigate a possible correlation between the pH of the water and the life span. Use a suitable chart type to visualize this. Provide a logical title together with axis titles and units. Is there a correlation?
p <- ex1_cleaned %>% 
  ggplot(aes(x = ph_of_water, y = life_span)) +
  geom_point(size = 3, color = "darkgreen") +
  labs(
    title = "Life Span as a function of pH",
    x = "pH of the water",
    y = "Life Span (years)"
  )
p

Exercise 2

This time we will analyse some weather data from the KNMI. Browse to KNMI - Uurgegevens van het weer in Nederland. Download a dataset from 1951-1960 for the weather station at Eelde.

  1. Load the data using RStudio. Note: you need to use some tweaks to load the data.
header<- c("STN", "YYYYMMDD", "HH", "DD", "FH", "FF", "FX", "T", "T10N", "TD", "SQ", "Q", "DR", "RH", "P", "VV", "N", "U", "WW", "IX", "M", "R", "S", "O", "Y")
ex2 <- read_csv("./data/exercise02/uurgeg_280_1951-1960/uurgeg_280_1951-1960.txt", skip=33, col_names = header)
formatted_table(head(ex2))
STN
dbl
YYYYMMDD
dbl
HH
dbl
DD
dbl
FH
dbl
FF
dbl
FX
lgl
T
dbl
T10N
lgl
TD
dbl
SQ
lgl
Q
lgl
DR
dbl
RH
dbl
P
dbl
VV
dbl
N
dbl
U
dbl
WW
dbl
IX
lgl
M
dbl
R
dbl
S
dbl
O
dbl
Y
dbl
280 19510101 1 140 67 0 NA -47 NA -55 NA NA NA NA 9980 NA NA 93 NA NA NA NA NA NA NA
280 19510101 2 140 67 0 NA -41 NA -50 NA NA NA NA 9976 NA NA 93 NA NA NA NA NA NA NA
280 19510101 3 140 67 62 NA -34 NA -43 NA NA NA NA 9963 NA 8 93 5 NA NA NA NA NA NA
280 19510101 4 140 67 67 NA -32 NA -41 NA NA NA NA 9951 NA 8 93 5 NA 0 0 0 0 0
280 19510101 5 120 72 62 NA -26 NA -30 NA NA NA NA 9940 NA 8 97 5 NA 0 0 0 0 0
280 19510101 6 120 72 62 NA -17 NA -24 NA NA NA NA 9934 NA 8 94 5 NA 0 0 0 0 0
  1. Find the lowest temperature and highest temperature (at 1.5 m height) using formulas in degrees Celsius (note: read the column info in the text file)!
min(ex2$T)/10
## [1] -22.9
max(ex2$T)/10
## [1] 33.1
  1. At what dates were these temperatures observed? Use formulas to get the answer.
ex2 %>%
  filter(T == min(T)) %>%
  formatted_table()
STN
dbl
YYYYMMDD
dbl
HH
dbl
DD
dbl
FH
dbl
FF
dbl
FX
lgl
T
dbl
T10N
lgl
TD
dbl
SQ
lgl
Q
lgl
DR
dbl
RH
dbl
P
dbl
VV
dbl
N
dbl
U
dbl
WW
dbl
IX
lgl
M
dbl
R
dbl
S
dbl
O
dbl
Y
dbl
280 19560216 4 0 5 0 NA -229 NA -243 NA NA NA NA 10147 6 2 87 48 NA 1 0 0 0 0
ex2 %>%
  filter(T == max(T)) %>%
  formatted_table()
STN
dbl
YYYYMMDD
dbl
HH
dbl
DD
dbl
FH
dbl
FF
dbl
FX
lgl
T
dbl
T10N
lgl
TD
dbl
SQ
lgl
Q
lgl
DR
dbl
RH
dbl
P
dbl
VV
dbl
N
dbl
U
dbl
WW
dbl
IX
lgl
M
dbl
R
dbl
S
dbl
O
dbl
Y
dbl
280 19590709 16 290 21 15 NA 331 NA 169 NA NA 0 0 10138 58 4 38 5 NA 0 0 0 0 0
  1. A tropical temperature is defined as a temperature of 30 °C or higher. How many tropical temperatures are in the dataset (at 1.5 m height)?
ex2 %>%
  filter(T > 300) %>%
  nrow()
## [1] 23
  1. There could be multiple tropical temperatures on the same day. How many tropical days are within the data set (at 1.5 m height)? Hint: use group_by and summarize for this.
ex2 %>%
  group_by(YYYYMMDD) %>%
  summarise(daily_max = max(T)) %>%
  filter(daily_max >= 300) %>%  
  nrow()
## [1] 7
  1. What was the average temperature in 1951? Use formulas to achieve this.
ex2 %>%
  filter(YYYYMMDD >= 19510101 & YYYYMMDD <= 19511231) %>%
  summarise(lowest_temp_celsius = mean(T) / 10) %>%
  formatted_table()
lowest_temp_celsius
dbl
8.974132

Exercise 3

Use the dataset from Our World in Data
Download vaccinations.csv.
This dataset contains daily vaccination figures per country worldwide, with columns such as date, location, total_vaccinations, people_vaccinated, people_fully_vaccinated, daily_vaccinations, etc.

  1. Load the data In RStudio.
ex3 <- read_csv("./data/exercise03/vaccinations.csv")
formatted_table(head(ex3))
location
chr
iso_code
chr
date
date
total_vaccinations
dbl
people_vaccinated
dbl
people_fully_vaccinated
dbl
total_boosters
dbl
daily_vaccinations_raw
dbl
daily_vaccinations
dbl
total_vaccinations_per_hundred
dbl
people_vaccinated_per_hundred
dbl
people_fully_vaccinated_per_hundred
dbl
total_boosters_per_hundred
dbl
daily_vaccinations_per_million
dbl
daily_people_vaccinated
dbl
daily_people_vaccinated_per_hundred
dbl
Afghanistan AFG 2021-02-22 0 0 NA NA NA NA 0 0 NA NA NA NA NA
Afghanistan AFG 2021-02-23 NA NA NA NA NA 1367 NA NA NA NA 33 1367 0.003
Afghanistan AFG 2021-02-24 NA NA NA NA NA 1367 NA NA NA NA 33 1367 0.003
Afghanistan AFG 2021-02-25 NA NA NA NA NA 1367 NA NA NA NA 33 1367 0.003
Afghanistan AFG 2021-02-26 NA NA NA NA NA 1367 NA NA NA NA 33 1367 0.003
Afghanistan AFG 2021-02-27 NA NA NA NA NA 1367 NA NA NA NA 33 1367 0.003
  1. Create a chart showing the progression of people_fully_vaccinated_per_hundred (in other words, the percentage) over time for the Netherlands. Filter the data accordingly. Provide a logical title together with axis titles and units.
p <- ex3 %>% 
  filter(location == "Netherlands") %>%
  ggplot(aes(x = date, y = people_vaccinated_per_hundred)) +
  geom_point(size = 3, color = "darkgreen") +
  labs(
    title = "Cummulative percentage of vaccinated people in The Netherlands",
    x = "year",
    y = "percentage"
  )
p

  1. Provide a table with the max people_fully_vaccinated_per_hundred per country. Note that the numbers above 100 are in the dataset because of various reasons (e.g. boosters counted as full vaccination, some small countries (like Gibraltar or San Marino) vaccinated people who are not residents etc.).
summ_max_per_country <- ex3 %>%
  group_by(location) %>%
  summarise(vacc_max = max(people_fully_vaccinated_per_hundred, na.rm = "NA"))
formatted_table(head(summ_max_per_country))
location
chr
vacc_max
dbl
Afghanistan 44.67
Africa 32.41
Albania 45.01
Algeria 14.43
Andorra 67.01
Angola 27.00

The end…


⬆️ Back to Top


This web page is distributed under the terms of the Creative Commons Attribution License which permits unrestricted use, distribution, and reproduction in any medium, provided the original author and source are credited. Creative Commons License: CC BY-SA 4.0.