One of the best ways to start learning to use the R console is as a calculator. Try typing the following at the R console and verify that you get the same answers:
2 + 2 # This should equal 4
## [1] 4
Did you notice my use of the
#
to add some commentary to my code? The#
character, called a hash or pound character tells R to ignore the rest of the line because it was written for humans. They are also used when displaying the output in our exercises so that you could easily cut and paste a section of several continous statements without causing a problem with the output. As you can see in the output we use two#
but this is not requried as R would ignore anything after the first one.
3 + 4 + 6
## [1] 13
20 - 4.2
## [1] 15.8
100 - 20 - 5
## [1] 75
2 * 2
## [1] 4
5 * 4 * 3 * 2 * 1
## [1] 120
25 / 5
## [1] 5
3 / 5
## [1] 0.6
What do you get when you divide by zero?
What does the operator %%
do? Don’t look it up - try to figure it out by experimenting with different inputs. For now, keep only use integers and keep the left number bigger than the right one. Here is one example of the type of things you should try:
12 %% 5
Try to think of a situation where the operator %%
might be useful for some procedure or process?
(3 * 4) + (5 * 6)
. In the absence of parentheses, most computer languages, including R, use a set of rules called precedence to determine which operation to do first. Although you might think left-to-right would be the rule, this is the rule only when two operators have equal precedence. Instead, certain operators take precedence over other operators and those with a higher precedence are executed first. Try some expressions like those below and figure out the precedence of the four main mathematical operators we learned about +
, -
, *
, /
.
2 + 3 * 4
3 / 2 * 5
Complete the following exercises in R and turn in your code (in an .R file named rithmatic_<yourlastname>.R) and answers (as comments within your .R file), e.g.,
# Question 1
3 + 4 + 5
# Answer: 12
# Question 2
...
In a couple of weeks we will learn a better way to combine code and the answers, but for now we will rely on this method.
What is the result of (2.12 + 4.2) * 1.001 / 2
?
What does the ^
operator do? Try to figure it out without looking it up. Give an example and describe in terms of another operator you have already learned.
What is the remainder of 6656127240 when divided by 9?
What does the %/%
operator do? Again, try to figure it out without looking it up. Only use whole numbers. Which operator that you have learned about is this operator the complement to?
What does R say the answer to zero divided by zero is?