Skip to content

Instantly share code, notes, and snippets.

@graebnerc
Last active June 10, 2024 08:08
Show Gist options
  • Save graebnerc/fa3b987235ef6d4a628325bbe705de75 to your computer and use it in GitHub Desktop.
Save graebnerc/fa3b987235ef6d4a628325bbe705de75 to your computer and use it in GitHub Desktop.
Solutions to the MCS tutorial exercises
Solutions to the exercises that are mentioned in the tutorial on Monte Carlo Simulations.
# 1. Write a for-loop that loops over the vector `c(1,2,3,4,5)` and computes the
# square root for each element.
input_vector <- c(1, 2, 3, 4, 5)
output_container <- rep(NA, length(input_vector))
for (i in seq_along(input_vector)){
square_root <- sqrt(input_vector[i])
output_container[i] <- square_root
}
output_container
# 2. Write a for loop that draws 10 numbers from a normal distribution with
# mean `0` and standard deviation `1`.
output_container <- rep(NA, 10)
for (i in seq_len(10)){
random_number <- rnorm(1)
output_container[i] <- random_number
}
output_container
# Note: the same could be accomplished without a loop via: rnorm(10)
# 3. Write a for-loop that loops over the columns of the tibble 'ex_tib', and
# computes the median of the elements in each column:
ex_tib <- tibble::tibble(
"a" = rnorm(5, mean = 5, sd = 2),
"b" = rpois(5, lambda = 3),
"c" = rcauchy(5, location = 3, scale = 2)
)
output_container <- rep(NA, ncol(ex_tib))
for (i in seq_along(ex_tib)){
col_median <- median(ex_tib[[i]])
output_container[i] <- col_median
}
output_container
# 4. Compute the square root for each element of the vector `c(1,2,3,4,5)`
# by using a map-function from `purrr`. In the first case, your solution
# should take the form of a list, in the second case an atomic vector of
# type `character`.
purrr::map(.x = c(1,2,3,4,5), .f = sqrt) # Results in a list
purrr::map_chr(.x = c(1,2,3,4,5), .f = sqrt) # Results in a character vector
# 5. Draw 10 numbers from a normal distribution with mean `2` and standard
# deviation `4`. Again, use a map-function from `purrr´ and return the result
# one time as an atomic vector of type `double` and one time of type `character`.
purrr::map_dbl(.x = 1:10, .f = ~rnorm(n = 1, mean = 2, sd = 4)) # Results in a double vector
purrr::map_chr(.x = 1:10, .f = ~rnorm(n = 1, mean = 2, sd = 4)) # Results in a character vector
# 6. Computes the median of the elements in each column of the tibble `ex_tib`
# as defined above. The result should come in form of a `list`.
ex_tib <- tibble::tibble(
"a" = rnorm(5, mean = 5, sd = 2),
"b" = rpois(5, lambda = 3),
"c" = rcauchy(5, location = 3, scale = 2)
)
purrr::map(.x = ex_tib, .f = median)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment