m<-matrix(1:12,nrow=3,ncol=4) # 3 by 4 matrix filled in columnwise
m
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
dim(m) # dimension of m
## [1] 3 4
nrow(m) # number of row in m
## [1] 3
ncol(m) # number of column in m
## [1] 4
matrix(1:12,nrow=3,byrow=T) # by row
## [,1] [,2] [,3] [,4]
## [1,] 1 2 3 4
## [2,] 5 6 7 8
## [3,] 9 10 11 12
m[2,] # select 2nd row
## [1] 2 5 8 11
m[,3] # select 3rd column
## [1] 7 8 9
m[2,3] # select an element
## [1] 8
m[1:2,2:4] # select submatrix
## [,1] [,2] [,3]
## [1,] 4 7 10
## [2,] 5 8 11
m[-2,] # exclude the second row
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 3 6 9 12
m1<-matrix(1:8,nrow=2) # create a 2x4 matrix m1
m2<-matrix(1:6,nrow=3) # create a 3x2 matrix m2
rbind(m,m1) # combine m and m1 row-wise
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
## [4,] 1 3 5 7
## [5,] 2 4 6 8
cbind(m,m2) # combine m and m2 column-wise
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 4 7 10 1 4
## [2,] 2 5 8 11 2 5
## [3,] 3 6 9 12 3 6
x<-c(1:3) # numeric vector
y<-c("a","b") # character vector
z<-matrix(1:6,nrow=2) # numeric matrix
w<-list(x,y,z) # define a list
w # display the list w
## [[1]]
## [1] 1 2 3
##
## [[2]]
## [1] "a" "b"
##
## [[3]]
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
w[[1]]
## [1] 1 2 3
w[[2]][2] # second elements of the second component of w
## [1] "b"
w[[3]][1:2,2] # element [1:2,2] of the third component of w
## [1] 3 4
names(w)<-c('x','y','z') # assign name to w
w
## $x
## [1] 1 2 3
##
## $y
## [1] "a" "b"
##
## $z
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
u<-unlist(w) # change w into a character vector u
u
## x1 x2 x3 y1 y2 z1 z2 z3 z4 z5 z6
## "1" "2" "3" "a" "b" "1" "2" "3" "4" "5" "6"
x<-c(4:1) # define a numeric vector
2*(x-1) # operate on each element of x
## [1] 6 4 2 0
x^2
## [1] 16 9 4 1
x<-c(4:1)
x%%3
## [1] 1 0 2 1