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
-  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.
-  5 4 6