Skip to content

Instantly share code, notes, and snippets.

@graebnerc
Created March 29, 2023 15:54
Show Gist options
  • Save graebnerc/bda112996a91b9fddee366eb5e713d91 to your computer and use it in GitHub Desktop.
Save graebnerc/bda112996a91b9fddee366eb5e713d91 to your computer and use it in GitHub Desktop.
Solutions to the in-class exercises of session 3 in the spring semester 2023.
Solutions to the in-class exercises of session 3 in the spring semester 2023.
# Task 1===============================
# Create a vector containing the numbers 2, 5, 2.4 and 11.
test_vec <- c(2, 5, 2.4, 11)
# What is the type of this vector?
typeof(test_vec)
# Replace the second element with 5.9.
# test_vec <- c(2, 5.9, 2.4, 11)
test_vec[2] <- 5.9
test_vec
# Add the elements 3 and 1 to the beginning, and the elements "8.0" and "9.2"
# to the end of the vector.
va_1 <- c(3, 1)
va_2 <- c("8.0", "9.2")
test_vec_extended <- c(va_1, test_vec, va_2)
test_vec_extended
# Transform this vector into the type integer. What happens?
typeof(test_vec_extended)
as.integer(test_vec_extended)
typeof(test_vec_extended)
test_vec_int <- as.integer(test_vec_extended)
typeof(test_vec_int)
# Task 2===============================
# What type is the following vector: "2", "Hello", 4.0, and TRUE
typeof(c("2", "Hello", 4.0, TRUE))
# What hierarchy is underlying this?
# See the tutorial for an explanation
# Task 3===============================
# Create a vector with the numbers from -8 to 9 (step size: 0.5)
v3_1 <- seq(-8, 9, by = 0.5)
v3_1
# Compute the square root of each element of the first vector using vectorisation. Anything that draws your attention?
v3_2 <- sqrt(v3_1)
# Task 4===============================
# Create a list that has three named elements: "A", "B", and "C"
# The element "A" should contain the square root of the
# numbers form -2 to 8 (step size: 1)
# The element "B" should contain the log of numbers between 2 and 4
# (step size: 0.5)
# The element "C" should contain letters from a1 to g7
# (hint: use the pre-defined vector letters and the function paste())
li_1 <- list(
"A"=sqrt(seq(-2, 8, by=1)),
"B"=log(seq(2, 4, by=0.5)),
"C"=paste(letters[1:7], 1:7, sep = "")
)
li_1
# Recommendable:
a_element <- sqrt(seq(-2, 8, by=1))
b_element <- log(seq(2, 4, by=0.5))
c_element <- paste(letters[1:7], 1:7, sep = "")
li_1 <- list(
"A"=a_element,
"B"=b_element,
"C"=c_element
)
li_1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment