Write a function called “multiply” that accepts two numbers as arguments and outputs the product of those two numbers when called as is demonstrated below.
multiply(3, 3)# [1] 9
Exercise: 5-B
Write an equation that returns the remainder of 12 divided by 8.
Exercise: 5-C
Write an equation that returns the remainder of 36 divided by 10.
Exercise: 5-D
Write a “while” loop that prints all even numbers from 0 to 10.
It’s possible for this task to be accomplished in several ways; however, the output of your program should always look like this:
# [1] 0# [1] 2# [1] 4# [1] 6# [1] 8# [1] 10
Exercise: 5-E
You are given a vector that looks like this:
numbers <-c(0:12)
Write a for loop that loops through your vector and prints any element greater than or equal to 3.
It’s possible for this task to be accomplished in several ways; however, the output of your program should always look like this:
Convert the following character variable to a variable with the data type “raw”:
x <-"Trevor rocks"
You should store your raw data in a variable named “raw_data”, print the data to the console, and check the data type with the “typeof” function. Your output should look like the following:
Create a variable named “spending” and give it a value of 120. Then create a variable named “budget” and give it a value of 100. Next, check whether spending is greater than budget and store the resulting logical data in a variable named “over_budget”. Finally, print the value of “over_budget” variable and check it’s data type with the “typeof” function.
Create a vector named “animal” and give it the following three values: “cow”, “cat”, “pig”. Create a second vector named “sound” and give it the following three values: “moo”, “meow”, “oink”. Finally, create a data frame named “animal_sounds” and assign each of these vectors to be a column.
After printing the resulting data frame to the console, you should get the following output:
# animal sound# 1 cow moo# 2 cat meow# 3 pig oink
Answers
Answer: 5-A
One way you could accomplish this task is demonstrated in the following solution.
A remainder is referred to as “modulus” in programming. We can use the “%%” operator to accomplish this. For this example, the output of your equation should be 4.
12%%8
[1] 4
Answer: 5-C
A remainder is referred to as “modulus” in programming. We can use the “%%” operator to accomplish this. For this example, the output of your equation should be 6.
36%%10
[1] 6
Answer: 5-D
Here’s one way you could write your while loop to achieve this output:
i <-0while (i <=10) {print(i) i <- i +2}
[1] 0
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
Answer: 5-E
Here’s one way you could write your for loop to achieve this output:
numbers <-c(0:12)for (number in numbers) {if (number >=3) {print(number) }}