##   1. How to Install R?
##   2. Basic Operators
##   3. Matrix Algebra
##   4. Generate data from the distribution
##   5. Example (OLS)
##   6. R Resources
##   7. Exercise


##   2. Basic Operators
#Creating variables
x <- 10 # x equals to 10
y <- 5  # y equals to 5
x+y
x-y
x*y
x/y
x^y

#delete all variables in memory
rm(list=ls(all=TRUE))
x



##   3. Matrix Algebra
#Creating vectors
vec1 <-seq(from = 1, to = 20, by = 2)
vec1
vec2 <-seq(from = 2, to = 20, 2)
vec2

#add a constant to vec1
vec3 <-vec1+1 
vec3

#addition
vec4 <-vec2+vec3
vec4

#Simple multiplication
#1. Same length 2. element times element
vec5 <-vec1*vec2
vec5

#Inner product (%*%)
vec5 <-vec1 %*% vec2
vec5

#Outer product (%o%)
vec5 <-vec1 %o% vec2
vec5

# other useful functions, like 
# max(), min (), sum(), length()
# median(), var(), sort()

#Combine vectors
M1 <-c(vec1, vec2)  #combine values into a vector
M1 

M1 <-cbind(vec1, vec2) #combine by columns
M1

M1 <-rbind(vec1, vec2) #combine by rows
M1

#Create a matrix (many ways)
Mij <-rbind(c(1, 2, 3), c(4, 5, 6))
Mij

Mij <-cbind(c(1, 2, 3), c(4, 5, 6))
Mij

Mij <-matrix(seq(1, 6), ncol = 2)
Mij

I5 <-diag(1, nrow = 5, ncol = 5)
I5

#Inverse of a matrix (only square matrices can be inverted)
x <-matrix(c(1, 2, 3, 4), ncol = 2)
x
solve (x)

#Attributes of a vector
x <-cbind(c(1, 2, 3), c(4, 5, 6))
x
dim(x) #dimension of x
t(x)   #transpose of x



##   4. Generate data from the distribution
# Here, we take uniform, normal, t, Chi-square distribution
# for example

#n is the number of data
#runif(n, min=0, max=1)
runif(50,min=0,max=1)

#rnorm(n, mean=0, sd=1)
x <-rnorm(1000, mean=0, sd=1)

#rt(n, df)
y <-rt(1000, 1)

#rchisq(n,df)
z <-rchisq(100, 2)

hist(z)



##   5. Example (OLS)
#Use R build?in function lm()
# OLS
rm(list=ls(all=TRUE))
n = 20
x <-rnorm(n)
b1 <-2
b2 <-10
y <- b1 + b2*x + rnorm(n, 0, 1)
lm(y~x)
summary(lm(y~x))
b_hat_ols <-coef(lm(y~x))
plot(x, y)
abline(b_hat_ols[1], b_hat_ols[2], col = "red")

# Calculate OLS coefficients by ourselves
b <-t(matrix(c(b1, b2), ncol = 2))
x <-matrix(c(rep(1, n), x), ncol = 2)
xx_inv <-solve((t(x)%*%x))
b_hat <-xx_inv%*%t(x)%*%y

##   6. R Resources (Useful Links)
# http://www.statmethods.net/index.html
# http://rwiki.sciviews.org/doku.php?id=links%3Alinks
# https://sites.google.com/site/rprojectnotes/






 




