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.

x<- c (10,20,30)
y<- c (1,2,3)
z<- 50
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
[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
[1] -0.5440211  0.9129453 -0.9880316
[1] -0.8390715  0.4080821  0.1542514
[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.

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

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:


> A+D
[1] 35 52 37
Warning message:
In A + D : longer object length is not a multiple of shorter object 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:

[1] 90

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.

A <- matrix (c (1 ,2 ,3 ,4) ,2 ,2)
B <- matrix (c (50 ,60 ,70 ,80) ,2 ,2)

> A
     [,1] [,2]
[1,]    1    3
[2,]    2    4
> B
     [,1] [,2]
[1,]   50   70
[2,]   60   80

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.

C <- matrix (c (50 ,60 ,70 ,80, 90,100) ,3 ,2)

Error in A + C : non-conformable arrays

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.

> C
     [,1] [,2]
[1,]   50   80
[2,]   60   90
[3,]   70  100
> t(C)
     [,1] [,2] [,3]
[1,]   50   60   70
[2,]   80   90  100

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.

About Deepak George Pazhayamadom

I'm a fish biologist and a mathematical modeller. I have a wide range of research interests, mostly centered on fisheries resource management.

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

  1. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: