Directions

For this lab, you will create a single .R file called lab05.R. The following exercises will ask you to write code. Place all requested code in this .R file separated by comments which indicate which code corresponds to which exercise.

Submit your lab to the corresponding assignment on Canvas. You have unlimited attempts before the deadline. Your final submission before the deadline will be graded.


Grading

This lab will be graded based on a mix of correctness and completion. Each exercise is worth 3 points. For each exercise that you demonstrate a good-faith effort to complete, you will receive at least one point. Because there are only two exercises, by turning in the lab you will start with four points.


Exercise 1 (Perfect, Abundant, and Deficient Numbers)

For this exercise, you will write four functions:

Each function takes as input a numeric vector of length 1. You do not need to check that this is the case, but the solution will contain code that checks for these conditions. We’ll be learning how to do this soon.

Test each of your functions with various inputs. Include these in your .R file after defining the functions. Also include the following code which will quickly test your functions for all numbers between 1 and 25.

data.frame(
  x = 1:25,
  perfect = sapply(1:25, is_perfect),
  abundant = sapply(1:25, is_abundant),
  deficient = sapply(1:25, is_deficient)
)

Exercise 2 (Luhn Algorithm)

For this exercise, you will write a function called is_valid which will check if a number (for example a credit card number) is “valid” according to the Luhn algorithm.

The algorithm starts with a positive integer with two or more digits, then does the following:

Your function should output TRUE if the input number is valid, and FALSE otherwise. The function has been started for you below. We also provide a helper function called split_digits that will likely be extremely useful. Include both of these functions in your .R file.

split_digits = function(x) {
  
  if (!is.numeric(x) | length(x) != 1 | trunc(x) != x) {
    stop("x stop be a numeric vector (that represents an \"integer\") of length 1")
  }

  return(as.numeric(strsplit(as.character(x), split = "")[[1]]))
  
}
is_valid = function(num) {
  
  if (length(split_digits(x = num)) < 2) {
    stop("input numbermust have at least two digits")
  }
  
  # delete this comment and place your code here
  
}

Also include the following lines in your .R file. Run them to check your function.

is_valid(num = 79927398713)      # should return TRUE
is_valid(num = 4539319503436467) # should return TRUE
is_valid(num = 8273123273520569) # should return FALSE