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:
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.
5-3in the R console to calculate the difference between 5 and 3.
5*3in the R console to calculate the product of 5 and 3.
5/3in the R console to divide 5 by 3
3^5in the editor to calculate 3 to the power 5.
26 %% 3to 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.
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.
# This is a comment
Get smart about tech at work.
As a non-technical professional, learn how software works with simple explanations of tech concepts. Learn more...