Thursday, October 20, 2011

R - Cheat sheet - Matrices

Return to the R Cheat sheet index page

cbind()  - Column bind - Equal length vectors can be combined to create a matrix.

> x<-c(1,2,3)
> y<-c(4,5,6)
> x
[1] 1 2 3
> y
[1] 4 5 6
> mm<-cbind(x,y);mm
     x y
[1,] 1 4
[2,] 2 5
[3,] 3 6
>

rbind() - As above but Row binding.

> mr<-rbind(x,y);mr
  [,1] [,2] [,3]
x    1    2    3
y    4    5    6
>

t( ) - Transpose the matrix.

> mm
     x y
[1,] 1 4
[2,] 2 5
[3,] 3 6
> t(mm)
  [,1] [,2] [,3]
x    1    2    3
y    4    5    6
>

Build a matrix in one instruction.
> m<-matrix(c(1,2,3,4,5,6), nrow=2);m

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
>

 or

> m<-matrix(c(1,2,3,4,5,6), nrow=2, byrow=T);m
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
>

Matrix multiplication
m1 %*% m2 - multiply matrix m1 with matrix m2

> m1<-matrix(c(1,5,10,12), nrow=2);m1
     [,1] [,2]
[1,]    1   10
[2,]    5   12
> m2<-matrix(c(3,4,7,9), nrow=2);m2
     [,1] [,2]
[1,]    3    7
[2,]    4    9
> m1%*%m2
     [,1] [,2]
[1,]   43   97
[2,]   63  143

and using the * operator gives scalar multiplication.
> m1*m2
     [,1] [,2]
[1,]    3   70
[2,]   20  108
>


Solve the matrix
solve(m1)

> m1
     [,1] [,2]
[1,]    1   10
[2,]    5   12
>
> ms<-solve(m1)
> ms
           [,1]        [,2]
[1,] -0.3157895  0.26315789
[2,]  0.1315789 -0.02631579
>
> ms%*%m1
     [,1] [,2]
[1,]    1    0
[2,]    0    1
>


Eigenvalues and vectors

> m1
     [,1] [,2]
[1,]    1   10
[2,]    5   12
> eigen(m1)
$values
[1] 15.458236 -2.458236

$vectors
           [,1]       [,2]
[1,] -0.5688428 -0.9450825
[2,] -0.8224463  0.3268319

>






Getting elements from a matrix





diag(mm) - Diagonal

No comments:

Post a Comment