Site hosted by Angelfire.com: Build your free website today!

Matrix Algebra :

> m<-matrix(1:6,nrow=2,byrow=T)  # [ since we gave 6 data only, specifying row is only enough to create a matrix since S-plus / R can calculate the number of columns by itself]
> m
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
> dim(m)                      # [ Asks the dimension values of m]
[1] 2 3
> dimnames(m)             # [ Asks the dimension names of m]
NULL
> col0<- c("c1","c2","c3")
> row0<- c("r1","r2")
> x
[1] 1 2 3
> names(x)<-col0
> x
 c1 c2 c3
  1  2  3
> dimnames(m)<-list(row0,NULL)
> m
   [,1] [,2] [,3]
r1    1    2    3
r2    4    5    6
> dimnames(m)<-list(NULL,col0)
> m
     c1 c2 c3
[1,]  1  2  3
[2,]  4  5  6
> dimnames(m)<-list(row0,col0)
> m
   c1 c2 c3
r1  1  2  3
r2  4  5  6
> dimnames(m)
[[1]]:
[1] "r1" "r2"

[[2]]:
[1] "c1" "c2" "c3"

> m[1,3]                       # [ Asks the value of 1st row and 3rd column of m]
[1] 3
> m["c2","r1"]
Error in m["c2", "r1"]: Array subscript (3) out of bounds, should be at most 2
Dumped
> m["r1","c2"]   # [ Asks the value of 1st row and 2nd  column of m by names]
[1] 2
> m[,"c2"]                    # [ Asks the vector values of 2nd  column of m]
 r1 r2
  2  5
> m[,1]
 r1 r2
  1  4
> m[2,]
 c1 c2 c3
  4  5  6
> m[2,2:3]
 c2 c3
  5  6
> m["r1","c2"]<-(-100)             # [inputs new value -100]
> m
   c1   c2 c3
r1  1 -100  3
r2  4    5  6
> m["r1","c2"]<-2
> m
   c1 c2 c3
r1  1  2  3
r2  4  5  6
> m[,2]/m[,1]
 r1   r2
  2 1.25
> m[2,]/m[1,]
 c1  c2 c3
  4 2.5  2
> c4<-c(4,6)
> m1<-cbind(m,c4)                  # [combines c4 as a new column of  m]
> m1
   c1 c2 c3 c4
r1  1  2  3  4
r2  4  5  6  6
> r3<-c(4,5,7)
> m2<-rbind(m,r3)
> m2
   c1 c2 c3
r1  1  2  3
r2  4  5  6
r3  4  5  7
> m2-> sqr
> ndim <- array(1:24,c(3,4,2))
> ndim

, , 1
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

, , 2
     [,1] [,2] [,3] [,4]
[1,]   13   16   19   22
[2,]   14   17   20   23
[3,]   15   18   21   24

Back to Index page