R/exercise_1_2.R

Defines functions exercise_1_2

Documented in exercise_1_2

#' ISWR exercise 1.2
#'
#' @description Solution to exercise 1.2 from Basics in Dalgaard P. Introductory
#' statistics with R. New York : Springer; 2008.
#'
#' @description “If `x` is a factor with `n` levels and `y` is a length `n` vector, what
#' happens if you compute `y[x]`?”
#'
#' @param x A factor with `n` levels.
#' @param y A length `n` vector.
#'
#' @return Returns answer to exercise.
#' @import tidyverse
#' @export
#'
#' @examples
#' exercise_1_2(factor, vector)
exercise_1_2 <- function(x, y) {

  # Make sure both arguments are of the correct type
  if (!is.factor(x) || !is.vector(y)) {
    stop("First argument must be a factor and second argument must be a vector.")
  }

  # Make sure both x’s number of levels are the same as y’s length
  if (x %>% levels() %>% length() != length(y)) {
    stop("First argument’s number of levels need to be equal to second argument’s length.")
  }

  y[x]
}
JonasEngstrom/prexRiswr documentation built on Dec. 18, 2021, 1:41 a.m.