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
This exercise is part of the course
Introduction to R for Finance
Learn essential data structures such as lists and data frames and apply that knowledge directly to financial examples.
Get comfortable with the very basics of R and learn how to use it as a calculator. Also, create your first variables in R and explore some of the base data types such as numerics and characters.
Exercise 1: Welcome to Introduction to R for Finance!Exercise 2: Your first R scriptExercise 3: Arithmetic in R (1)Exercise 4: Arithmetic in R (2)Exercise 5: Assignment and variables (1)Exercise 6: Assignment and variables (2)Exercise 7: Financial returnsExercise 8: Financial returns (1)Exercise 9: Financial returns (2)Exercise 10: Basic data typesExercise 11: Data type explorationExercise 12: What's that data type?What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.