when sample size goes to infinity

# Expectation = Mean when sample size goes to infinity.
par(mfrow=c(3,1),mar = c(3,4,1,1))
# The expectation of chi square here equals the df
x=rchisq(n=10,df=5)
hist(x)
abline(v=mean(x), col = "red")

x=rchisq(n=100,df=5)
hist(x)
abline(v=mean(x), col = "red")

x=rchisq(n=10000,df=5)
hist(x)
abline(v=mean(x), col = "red")

# Variance
## change the number size
n=100
x=rnorm(n,100,5)
hist(x)
c(min(x),max(x))
## [1]  89.78675 112.72914
sum(x-mean(x))/(n-1)
## [1] 3.875688e-15
sum((x-mean(x))^2)/(n-1)
## [1] 28.81382
sqrt(sum((x-mean(x))^2)/(n-1))
## [1] 5.367851
# var()

Covariance

# define 3 random variable
n=10000
a=rnorm(n,100,5)
x=a+rpois(n, 100)
y=a+rchisq(n,5)
z=a+rt(n,100)
par(mfrow=c(3,1),mar = c(3,4,1,1))
plot(x,y)
plot(x,z)
plot(y,z)

var(x)
## [1] 125.3077
var(y)
## [1] 34.53482
var(z)
## [1] 25.81374
cov(x,y)
## [1] 25.55683
cov(x,z)
## [1] 25.3954
cov(y,z)
## [1] 24.83769
W=cbind(x,y,z)
dim(W)
## [1] 10000     3
cov(W)
##           x        y        z
## x 125.30771 25.55683 25.39540
## y  25.55683 34.53482 24.83769
## z  25.39540 24.83769 25.81374
var(W)
##           x        y        z
## x 125.30771 25.55683 25.39540
## y  25.55683 34.53482 24.83769
## z  25.39540 24.83769 25.81374
cor(W)
##           x         y         z
## x 1.0000000 0.3884986 0.4465197
## y 0.3884986 1.0000000 0.8318732
## z 0.4465197 0.8318732 1.0000000

Matrix manipulations

a=matrix(seq(10,60,10),2,3)
b=matrix(seq(1,6),2,3)
a
##      [,1] [,2] [,3]
## [1,]   10   30   50
## [2,]   20   40   60
b
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
# add
a+b
##      [,1] [,2] [,3]
## [1,]   11   33   55
## [2,]   22   44   66
# subtraction
a-b
##      [,1] [,2] [,3]
## [1,]    9   27   45
## [2,]   18   36   54
# (dot)product
a*b
##      [,1] [,2] [,3]
## [1,]   10   90  250
## [2,]   40  160  360
# (dot)division
a/b
##      [,1] [,2] [,3]
## [1,]   10   10   10
## [2,]   10   10   10
# matrix multiplication
c=matrix(c(1,1,1,1,3,4,2,1,30,50,40,25),4,3)
b=matrix(c(20000,10000,1000,1000,300,20),3,2)
t=c%*%b
# inverse
t = t[1:2,1:2]
ti=solve(t)
ti
##               [,1]          [,2]
## [1,] -0.0001684211  0.0001315789
## [2,]  0.0057894737 -0.0042105263
ti %*% t
##              [,1]         [,2]
## [1,] 1.000000e+00 5.551115e-17
## [2,] 5.684342e-14 1.000000e+00
t%*%ti
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
# transpose
c=matrix(c(1,1,1,4,30,50),2,3)
c
##      [,1] [,2] [,3]
## [1,]    1    1   30
## [2,]    1    4   50
t(c)
##      [,1] [,2]
## [1,]    1    1
## [2,]    1    4
## [3,]   30   50
# Properties of transpose
A=matrix(c(1,1,1,4,30,50),2,3)
B=matrix(c(1000,300,20,20000,10000,1000),3,2)
t(A%*%B)
##       [,1]   [,2]
## [1,]  1900   3200
## [2,] 60000 110000
t(B)%*%t(A)
##       [,1]   [,2]
## [1,]  1900   3200
## [2,] 60000 110000