Saturday, October 27, 2007

Matrix, Array and List

### define a matrix
> A = matrix(c(1,2,3,4,5,6,7,8,9),ncol=3)
> A
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

### operations for matrix and array
diag(10) : identity matrix
t(A), A%*%B, crossprod(A,B) ; t(A)%*%B, outer(A,B) ; outer product, kronecker(A,B)
solve(A) : inverse matrix of A
solve(A,b) ; solve equations or invert matrices - solve(A)*b
svd(A) ; singular value decomposition
qr(A) ; QR decomposition
qr(A)$rank ; rank of A
eigen(A) ; eigenvalues
chol(A) ; Choleski decomposition

### matrix(data=NA, nrow=, ncol=, byrow=F)
> mm<-matrix( scan("mfile"), ncol=5, byrow=T) // read all rows from the file
> M[1,] // row1
> M[,2] // column2
> M[1,2] // element row1, column2
> M[,c(1,3,5)] // column 1, 3, 5
> M[,-c(1,5)] // remove column 1, 5
> M[M[,3]>7,1]
> X1 <- matrix(1:10,ncol=2)
> Y1 <- matrix(1:20,ncol=4)
> Z1 <- cbind(X1,Y1) // column bind
> rbind(X1,Y1[,1:2]) // row bind
> colnames(marks)
> marks["test3"]
> aa <- array(c(1:6,7:12,13:18),dim=c(2,3,3))
> aa <- 1:18 ; dim(aa)<-c(2,3,3)
> col(aa)
> row(aa)

# matrix, array
length( ), ncol( ), nrow( ), mode( ), dim( ), dimnames( )

### list()
> alist<-list(c(0,1,2),1:10)
> alist[[1]]
> alist[[2]]

> blist <- list(c("A","B","C"),1:5,"Name")

> clist <- list(x=matrix(1:10,ncol=2),y=c("A","B"),z=blist)
> clist$x
> clist$x[1:3,1:2]
> clist$z[[2]]

### list -> array
array(unlist(aa), dim=c(3,3,10))

No comments: