Basic calculation in RHow to use basic operations in R

R commander may be seen as an advanced calculator perfectly suited to solve statistics and mathematical problems. There are also some basic mathematical functions. They will be explained in this Basic operations in R tutorial. It is needed to go over the Collections in R and Files and tables in R tutorials before continuing with this basic R operations tutorial. On the 2 previously mentioned tutorials you have learned how to add data to collections/tables and in this tutorial you will learn how to do basic operations on this collections and on individual variables.

Basic operations in R

When launching R commander you can see a command prompt (" > "). You have to enter all your commands behind this prompt.

It is easy to use basic operations in R. It is just plus, minus, multiply, divide, square root and exponent. Note that R follows the order of operations.

A few examples using operations in R without variables or collections:

  • Plus: 5 + 5
  • Minus: 5 - 3
  • Multiply: 5 * 3
  • Divide: 5/3
  • Square root: sqrt(100) # Note that this calls the sqrt function.
  • Exponent: 5^3
  • Order of operations: (2*2+(2-5)^3)/2

Basic operations on collections in R

In the previous tutorials you have learned how to add data to collections. Now you will learn how to do basic operations to this data. We will be working with a vector of numbers on this tutorial to explain how basic operations work in combination with collections.

  • a = c(1,2,3)   # Creates the collection a
  • a * 5   # Multiplies all individual items in a by 5
  • [1] 5 10 15

It is very important to see that all individual items in the collection a are multiplied by 5. So 1 is multiplied by 5, 2 is multiplied by 5, ... . This may be very handy for doing conversions. For example: if you have got a collection with speeds in mph and you want to change them to kmph then you just have to multiply the entire collection by 1.609 to change all values to kmph. Taking the square root etc from collections follow the same principle.

It is also possible to do basic operations between 2 different collections. With the following example we will show you how to add the elements from the previously created collection a to another collection named b. Know that both collections have to have the same length to be able to do basic operations in R between different collections.

  • b = c(4,2,3)   # Creates the collection a
  • a + b   # Ads all numbers in a to the numbers in a.
  • [1] 5 4 6
R tutorial overview Previous tutorial: Files and tables in R Next tutorial: Functions in R