# 1. Matrix Algebra
set.seed(123)
A=matrix(sample(100,15),nrow = 5,ncol = 3)
set.seed(234)
B=matrix(sample(100,15),nrow = 5,ncol = 3)
set.seed(321)
X=matrix(sample(100,4),nrow = 2,ncol = 2)
set.seed(213)
b=matrix(sample(100,15),nrow = 5,ncol = 1)
# + - * / ^
A+2
A*2
A^2
# Matrix multiplication
t(A)%*%B # 转置的A矩阵乘以B
# Return a vector containing the column means of A
colMeans(A)
# Return a vector containing the column sums of A
colSums(A)
# Return a vector containing the row means of A
rowMeans(A)
# Return a vector containing the row sums of A
rowSums(A)
# Matrix Crossproduct
# A'A
crossprod(A)
# A'B
crossprod(A,B)
# Inverse of A where A is a square matrix
solve(X)
# Sloves for vector x in the equation b=Ax
# a=Xv
a=matrix(1:4,nrow = 2,ncol = 2)
v=solve(X,a)
v
# Returns a vector containing the elements of the principal diagnoal
diag(X)
# Creates a diagonal matrix with the elements of x in the principal diagonal
diag(c(1,2,3,4))
# If k is a scalar,this creates a k×k identity matrix
diag(5)
# Eigenvalues and eigenvectors of A
eigen(X)
# 2. Factor
Factor=factor(rep(c(1:3),times=5))
Factor
X=sample(100,15)
tapply(X, Factor, mean)
rbind(X,Factor)
boo=rbind(X,Factor)[2,]==2
which(boo)
rbind(X,Factor)[1,which(boo)]
sum(rbind(X,Factor)[1,which(boo)])/length(which(boo))