# Easy R for M.F.Sc students – Part 4 (Computation with vectors and matrices)

This chapter would be the least complicated I hope. Basically we will learn many of the default R commands to do simple mathematics.

**Operators in R**

Operators in R are essentially the school standard mathematical symbols we use for any simple calculation. The different basic arithmetic operators (Syntax given inside the round brackets) used in R are: Addition (+), Substraction (-), Multiplication (*), Division (/), Exponent (^), Reminder after dividing A by B (A%%B), Quotient after dividing A by B (A%/%B). Apart from these, there are logical operators such as: Greater than (>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=), Equal to (==), Not equal to (!=), A or B (A | B), A and B (A & B).

**Functions in R to do Maths**

There are functions available to do mathematics and statistics in R. They are different from operators. Data can go inside the round brackets of the function in any type form: vector, matrix or array. But be careful and always do a trial with smaller data sets before using huge and long data sets (This is a very obvious and widely used bug fixing trick).

Let’s take one number, ‘z’ and two vectors, ‘x’and ‘y’ and see what does the different functions do with it. Only the very basic and more frequently used functions are demonstrated. You can easily find a complete list by a google search.

sum (y) # Sum of the elements in y [1] 6 prod (x) # Product of the elements in x [1] 6000 max (y) # The largest element in y [1] 3 min (y) # The smallest element in y [1] 1 range (x) # The range of elements in x [1] 10 30 mean (x) # The mean of elements in x [1] 20 median (x) # The median of the vector x [1] 20 log (z) # Log of the number z [1] 3.912023 log (x) # The log of all elements in vector x [1] 2.302585 2.995732 3.401197 log10 (x) # The log of all elements in vector x to the base 10 [1] 1.000000 1.301030 1.477121 sd (x) # Standard deviation of the vector x [1] 10 var (x) # Variance of the vector x [1] 100 cor (x,y) # Correlation between the vector x and y [1] 1 round (x,n) # Round the fraction 'x' to n decimal points round(2.34567,2) [1] 2.35 abs (x) # The absolute value of x abs (-0.00234) [1] 0.00234 cumsum (x) # Cumulative sum of the elements in x [1] 10 30 60 # Trignometric functions of x sin(x) [1] -0.5440211 0.9129453 -0.9880316 cos(x) [1] -0.8390715 0.4080821 0.1542514 tan(x) [1] 0.6483608 2.2371609 -6.4053312 exp (z) # Exponential function of x [1] 5.184706e+21

**How does math functions work in R ?
**

Start with a new R window and try following as you go. Feel free to experiment with your own ideas. If you seems like screwed somewhere, the best way would be to press ESC key on your keyboard in the top left corner.

I will try to demonstrate this with doing **Addition**

Any two individual numbers can simply be added as following:

> 35+50 [1] 85

But it is slightly different while using vectors. Let’s create a vector and use addition:

> A<-c(1,2,3) > A+3 [1] 4 5 6

In the above example, the vector ‘A’ was added to the number 3. Essentially, all the elements in the vector was added with 3. Now let’s look an example of addition with two vectors.

When two vectors were used, each element in one vector added to the respective element in the other vector. So infact, this will work only if two vectors are of equal length. To demonstrate, let’s see what happens if we attempt to add two vectors of unequal length:

What we got is an error message. So while addition between two data, it is important that all of them consists equal number of elements.

You can also use the ‘sum ( )’ function to add any number of data within the brackets. If we just want to add all the elements in vector A and vector D, the following can be used:

This sounds simple. But it is important to not get confused, what a ‘sum ( )’ function does how different it is from using the operator character ‘+’.

Essentially, in the above example, R reads like

sum ( c (1,2,3) , c (34,50) )

All math functions works in the same style. So watch out the traps while you code them. Always work with small numbers before using them into your real hard core stuff.

**Mathematical computation with matrices**

So far, we dealt only with vectors. Now let’s see how to do matrix operations. I hope you might haven’t forgotten how to create a matrix (Please see Part 3 of the series). Let’s create two matrices, A and B.

Now let’s do an** addition and substraction** with this two matrices

> A+B [,1] [,2] [1,] 51 73 [2,] 62 84 > A-B [,1] [,2] [1,] -49 -67 [2,] -58 -76

You can see that, each element in the matrix added/ substracted to the respective element in the other matrix. i.e., A[row,column] added to B[row,column]. So again, these operations only work if they are in the right dimensions. Let’s see what happens if there is a mistake. Create a new matrix, ‘C’ with three rows and add it with A.

There you got an error message. But, just like the vector addition, we do can add all elements of a matrix with a single number. See below:

> A+8 [,1] [,2] [1,] 9 11 [2,] 10 12

That’s cool, isn’t it !! Let’s now try **matrix multiplication**.

Just to recall your memory, how matrices are multiplied:

To multiply two matrices in R, use the following operators:

> A%*%B [,1] [,2] [1,] 230 310 [2,] 340 460 > B%*%A [,1] [,2] [1,] 190 430 [2,] 220 500

Be careful that product of A and B is different from B and A. Matrices can also be multiplied with a single number just like the addition. All elements in the matrix will get multiplied.

> A*5 [,1] [,2] [1,] 5 15 [2,] 10 20

It is also easy in R to **transpose a matrix**: See the function used below.

In this part, we covered the most important functions with regard to mathematical operations and that could possibly be more useful with your research in fisheries. Ofcourse, more advanced stuffs can always be learned by yourself from internet. If you have made this far, you might be quite independent to go yourselves by now. My next two parts will deal with organizing data and ways to sort, extract and modify your data for analysis.

If you like my tutorial, feel free to leave a feedback. I would be more than happy to hear from you. See you in next part. Bye.

Posted on January 19, 2012, in Bio-Statistics and Analysis. Bookmark the permalink. 2 Comments.

Good One.. A good effort.. keep it up.. waiting for the next part.. thank you!!!

Happy to know some one is reading my blogs 🙂

Traffic statistics is less impressive but just keep writing so I won’t forget them easily. Moreover, I can always come back to refer my own blogs while working with R.