R has no direct way to create an arbitrary matrix. You have to first list all the entries of the matrix as a single vector (an m by n matrix will need a vector of length mn) and then fold the vector into a matrix. To create
   	
    1	2
    3	4

we first list the entries column by column to get

    1, 3, 2, 4. 

To create the matrix in R:

A = matrix(c(1,3,2,4),nrow=2)
A

The nrow=2 command tells R that the matrix has 2 rows (then R can compute the number of columns by dividing the length of the vector by nrow.) You could have also typed:

A <- matrix(c(1,3,2,4),ncol=2) #<- is same as =
A

to get the same effect. Notice that R folds a vector into a matrix column by column. Sometimes, however, we may need to fold row by row :

A = matrix(c(1,3,2,4),nrow=2,byrow=T)

The T is same as TRUE.

	Exercise: Matrix operations in R are more or less straight forward. Try the following.

A = matrix(c(1,3,2,4),ncol=2)
B = matrix(2:7,nrow=2)
C = matrix(5:2,ncol=2)
dim(B) #dimension
nrow(B)
ncol(B)
A+C
A-C
A%*%C #matrix multiplication
A*C  #entrywise multiplication
A%*%B
t(B)

Subscripting a matrix is done much like subscripting a vector, except that for a matrix we need two subscripts. To see the (1,2)-th entry (i.e., the entry in row 1 and column 2) of A type

A[1,2]

	Exercise: Try out the following commands to find what they do.

A[1,]
B[1,c(2,3)]
B[,-1]

Working with rows and columns
Consider the following.

A = matrix(c(1,3,2,4),ncol=2)
sin(A)

Here the sin function applies entrywise. Now suppose that we want to find the sum of each column. So we want to apply the sum function columnwise. We achieve this by using the apply function like this:

apply(A,2,sum)

The 2 above means columnwise. If we need to find the rowwise means we can use

apply(A,1,mean)


singular value decomposition (svd)
eigenanalysis (eigen)
finding determinants (det)
QR decomposition (qr)
Choleski factorization (chol)

which
which.min


