Performing Basic Math Operations in R

Now that you have R running on your system and you can see the R console, let’s start by having r do some basic arithmetic for us. We can perform all arithmetic operations in R as you would do on a regular calculator.

Let’s begin by clearing the console screen. To do so press CTRL+L. This will clear everything from console.

Consider the following arithmetic operators:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponentiation: ^
  • Modulo: %%

To calculate the sum of 3 and 5, simply type 3 + 5 in the console and hit Enter. R will compile what you
typed, calculate the result and print that result as a numerical value.

Similarly, you can type a string (which is entered in quotes) and hit enter and R will output the result as a string. R understands your input and distinguishes between character string and numerical value.

The other arithmetic operators work in the same way. Try the following in your R console.

  • Type 5-3 in the R console to calculate the difference between 5 and 3.
  • Type 5*3 in the R console to calculate the product of 5 and 3.
  • Type 5/3 in the R console to divide 5 by 3
  • Type 3^5 in the editor to calculate 3 to the power 5.
  • Type 26 %% 3 to calculate 26 modulo 3.

The last one, the modulo operation, finds the remainder after division of one number by another. The above expression 26 modulo 3 would evaluate to 2 because 26 divided by 3 leaves a quotient of 8 and a remainder of 2.

Adding comments

While writing programs, it is important to add comments in various places so that when you are reviewing a program in future, the comments can help you understand your program.

To add a comment, add the symbol # before the text that you want to show as comment.

For example:

# This is a comment

Please login to view this lesson.

With our free registration, you can access to all the lessons on finance, risk, data analytics and data science for finance professionals.

Sign in free