2012년 12월 14일 금요일

[R Study(Matrix - No5 ]

Today,  I am going to introduce a matrix. In practical terms, I am sure this lesson will be helpful in the real word.

We learned new concept a "Vector" in a previous chapter, but in reality, we handle more complex data set, and variable. "Matrix" is one of the useful data set we can make.

I'll show you how to make a simple matrix.

First, I can make a matrix using several vectors.



> Pencil <- c(1,2,3,4,5)
> Computer <- c(10,20,30,40,50)
> Tree <- c(100,200,300,400,500)
> Export_Item  <- cbind(Pencil,Computer, Tree)
> Export_Item
     Pencil Computer Tree
[1,]      1       10  100
[2,]      2       20  200
[3,]      3       30  300
[4,]      4      40  400
[5,]      5       50  500




> Export_Item  <- rbind(Pencil,Computer, Tree)
> Export_Item
                 [,1] [,2] [,3] [,4] [,5]
Pencil            1    2    3    4    5
Computer     10   20   30   40   50
Tree           100  200  300  400  500

# As you can see above, cbind binds vectors into a matrix by columns and
   rbind binds vectors into a matrix by rows


Second, we can make a matrix using matrix function.
See, by default vectors pour into a matrix by columns but it can be done by rows by
setting the option "byrow=T"


> matrix (1:15, nrow=5, ncol=3)
     [,1] [,2] [,3]
[1,]    1    6   11
[2,]    2    7   12
[3,]    3    8   13
[4,]    4    9   14
[5,]    5   10   15



> matrix (1:15,nrow=5, ncol=3,byrow=T)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12
[5,]   13   14   15
>



Now, you can calculate by matrix.


> Export_Item*Export_Item
          [,1]  [,2]  [,3]   [,4]   [,5]
Pencil       1     4     9     16     25
Computer   100   400   900   1600   2500
Tree     10000 40000 90000 160000 250000

> Export_Item-Export_Item
                 [,1] [,2] [,3] [,4] [,5]
Pencil          0    0    0    0    0
Computer    0    0    0    0    0
Tree            0    0    0    0    0

> Export_Item+Export_Item
                [,1] [,2] [,3] [,4] [,5]
Pencil          2    4    6    8   10
Computer    20   40   60   80  100
Tree          200  400  600  800 1000


If you want to change the first rows or column title into a new label.
Just do it like this.



> dimnames(Export_Item)[[2]]=c("JAN","FEB","MAR","APR","MAY")
> Export_Item
                JAN FEB MAR APR MAY
Pencil         1   2   3   4   5
Computer  10  20  30  40  50
Tree         100 200 300 400 500




> dimnames(Export_Item)[[1]]=c("Teenager","Woman","MAN")
> Export_Item
                JAN FEB MAR APR MAY
Teenager     1   2   3   4   5
Woman      10  20  30  40  50
MAN         100 200 300 400 500



I hope this lesson help your study..
see you next chapter.





댓글 없음:

댓글 쓰기