For this lab, you will create a single .R
file called lab04.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.
This lab will be graded based on a mix of correctness and completion. Each exercise is worth two points. For each exercise that you demonstrate a good-faith effort to complete, you will receive at least one point. Because there are only three exercises, by turning in the lab you will start with four points.
Write a function called fizz_buzz
. The function will take a single argument x
which is a numeric vector of any length.
The function should return a character vector of the same length as the input x
that is a modification of x
in the following ways:
x
is a multiple of 3
, replace it with "fizz"
.x
is a multiple of 5
, replace it with "buzz"
.x
is both a multiple of 3
and a multiple of 5
, replace it with "fizzbuzz"
.This vector will contain a mix of “numbers” and characters, so any numbers not replaced by "fizz"
, "buzz"
, or "fizzbuzz"
, will need to be characters like "42"
.
To demonstrate that your code is correct, also run (and place in your .R
file) the following lines after writing your function:
fizz_buzz(x = 1:5)
fizz_buzz(x = 10:20)
Note, the following will be useful:
1:10 %% 3
## [1] 1 2 0 1 2 0 1 2 0 1
The %%
operator is used to do modular arithmetic. In particular, when the above code returns 0
, those elements of 1:10
are divisible by 3
.
Write a function called is_leap
that takes as input a numeric vector of length one named year
that stores a year. (For simplicity, assume only integer values greater than 0 are used.)
Leap years occur:
Your function should output TRUE
if year
is a leap year, FALSE
otherwise.
In addition to your function, run it at least five times with different inputs to verify that it works. Include this in your .R
file.
Write a function called gen_mult_seq
that has three arguments:
first
: a numeric vector of length onemulti
: a numeric vector of length onelength
: an integer vector of length oneThe output of the function will be a numeric vector of length length
which contains a sequence of values.
first
.length
elements.first * multi
. The third element is the second element multiplied by multi
. And so on.There are many ways to accomplish this task (and try a few if you’re interested) but the intention of this exercise is for you to write a for
loop. (Clever math would allow you to avoid it.)
In addition to your function, run it at least five times with different inputs to verify that it works. Include this in your .R
file.