Published

February 7, 2024

Due 2/17/24 @ 11:59 PM

Use an RMD M408 Template to create the assignment.

You must comment all your code to receive credit.

Submit the *.html file to canvas.

Problem 1

Write a function that takes a vector as an input an returns a labeled list with the mean, median, and variance of the vector.

Answer
xsummary <- function(x){
  list(mean = mean(x),
       median = median(x),
       variance = var(x))
}

Problem 2

Write a function for the following equation:

\[ f(x, y, z) =\left\{\begin{array}{cc} x^2+\sqrt y & z = 0 \\ x^2+2x+3+ \log(y) & z = 1 \end{array}\right. \]

Include any error messages if necessary.

Answer
fxyz <- function(x, y, z){
  if (!z %in% c(0,1)){stop("z must be 0 or 1")}
  if (y<=0){stop("y must be greater than 0")}
  if (z ==0){
    return(x^2+sqrt(y))
  } else {
    return(x^2 + 2*x + 3 + log(y))
  }
}

Problem 3

Create a function that will give you the first x Fibonacci numbers. You must use a for loop.

Answer
fib <- function(x){
  post <- c(0,1)
  for(i in 3:x){
    post <- c(post, fib[i-2] + fib[i-1])
  }
  return(post)
}

Problem 4

Create a function that will randomly generate n numbers that are greater than x from a \(Pois(\lambda)\).

Answer
new_pois <- function(n, x, lambda){
  nn <- 0
  post <- c()
  while(nn < n){
    new <- rpois(1, lambda)
    if (new > x){
      post <- c(post, new)
      nn <- length(post)
    }
  }
  return(post)
}