Arithmetic in R (1)
Let's play around with your new calculator. First, check out these arithmetic operators, most of them should look familiar:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Exponentiation:
^
or**
- Modulo:
%%
You might be unfamiliar with the last two. The ^
operator raises the number to its left to the power of the number to its right. For example, 3^2
is 9. The modulo returns the remainder of the division of the number to the left by the number on the right, for example 5 modulo 3 or 5 %% 3
is 2.
Lastly, there is another useful way to execute your code besides typing in the R Console or pressing Submit Answer. Clicking on a line of code in the script, and then pressing Command + Enter
will execute just that line in the R Console. Try it out with the 2 + 2
line already in the script!
This is a part of the course
“Introduction to R for Finance”
Exercise instructions
- Some examples for addition, subtraction, and multiplication are shown for you.
- Type
4 / 2
in the script to perform division. - Type
2^4
to raise 2 to the power of 4. - Type
7 %% 3
to calculate 7 modulo 3. - Don't forget to press Submit Answer when you finish!
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Addition
2 + 2
# Subtraction
4 - 1
# Multiplication
3 * 4
# Division
# Exponentiation
# Modulo