Skip to content

Instantly share code, notes, and snippets.

@graebnerc
Last active March 30, 2023 13:49
Show Gist options
  • Save graebnerc/1a2d538cc5a0f250448cd58bbc59b054 to your computer and use it in GitHub Desktop.
Save graebnerc/1a2d538cc5a0f250448cd58bbc59b054 to your computer and use it in GitHub Desktop.
Lecture notes and solutions to the exercises of session 4 in the spring semester 2023
Lecture notes and solutions to the exercises of session 2 in the spring semester 2023
library(tibble)
# Task 1-------------------------------
# Create a factor with the levels "still", "medium", "sparkling",
# and arbitrary instances of the three levels
level_vector <- c("still", "medium", "sparkling")
level_vector_reversed <- c("sparkling", "medium", "still")
t1_factor <- factor(
x = c(rep("still", 4), rep("medium", 3), rep("sparkling", 2)),
levels=level_vector_reversed,
ordered = TRUE)
# Get the relative frequencies for "medium" of this factor
table(t1_factor) # absolute freqs
table(t1_factor)/length(t1_factor)
# Task 2-------------------------------
# Create a data frame with two columns, one called "nb" containing the
# numbers 1 to 5 as double, the other called "char" containing the
# numbers 6 to 10 as character
col_1 <- as.double(seq(1, 5))
col_2 <- as.character(seq(6, 10))
df_t2 <- data.frame(
"nb" = col_1,
"char" = col_2
)
df_t2
# Transform this data frame into a tibble!
dt_t2 <- tibble::as_tibble(df_t2)
dt_t2
tibble::is_tibble(dt_t2)
# Extract the second column of this tibble such that you have a vector
dt_t2[[2]]
dt_t2[["char"]]
# Advanced object types================
## Factors-----------------------------
# Define a factor:
f_1 <- factor(
x = c(rep("F", 4),
rep("D", 5),
rep("M", 3)),
levels = c("D", "F", "M")
)
f_1
levels(f_1) # Get the levels
# What happens if we do not specify levels explicitly?
# What happens if the vector contains elements not pre-specified as levels?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment