##R script for Exercise 1
##Fill "___" to complete the codes
##But don't forget to answer questions

## 1.
## a. 
x<-c("a", 2) 
class(x)
## [1] "character"
## b. 
x<-c(FALSE, TRUE, FALSE, TRUE, TRUE) 
y<-as.numeric(x)
y
## [1] 0 1 0 1 1
sum(x); mean(x)
## [1] 3
## [1] 0.6
## c. 
x<-c(1, 2, 3, 4)
x[c(TRUE, TRUE, FALSE, TRUE)]
## [1] 1 2 4
x[c(1, 1, 0, 1)]
## [1] 1 1 1
## d. 
x<-c(NA, FALSE)
class(x)
## [1] "logical"
y<-c(NA, NaN, FALSE)
class(y)
## [1] "numeric"
## 2. 
## a. 
mylist<-list(integer = 1:10, character = c("a", "c", "d"), 
             logical_value = c(TRUE, FALSE, FALSE, TRUE),
             real_number = c(2.5, 3.2, 1.79))
class(mylist)
## [1] "list"
## b. 
x<-unlist(mylist)
class(x)
## [1] "character"
## 3. 
## a. 
b<-c(10,4,6)
x<-c(2, 3, 1, 4, -2, 2, 5, 4, 1)
A<-matrix(x, 3, 3)
solve(A, b)
## [1]  3.3333333  1.6666667 -0.6666667
## b. 
x<-rep(1, times = 10)
y<- 0:99
A<-matrix(y, 10, 10)    ## Matrix I choose is a 10 x 10 matrix
t(x)%*%A%*%x
##      [,1]
## [1,] 4950
## c. 
myfun<-function(x){
  y<-0:x
  return(sum(y))
}

## Use myfun to calculate sum of 1, 2, ..., x = 99
x<-99
myfun(x)
## [1] 4950
## 4. 
## a. 
x<-rnorm(10); y<-rnorm(10)
all(x==y)
## [1] FALSE
## b. 
set.seed(1234); x<-rnorm(10); set.seed(1234); y<-rnorm(10)
all(x==y)
## [1] TRUE
## 5. 
## a. 
x<-rt(1000, df =200)
y<-rchisq(1000, df = 1)
z<-rnorm(1000, mean = 0, sd = 1)
w<-0.3+2*x+1.5*y+z
mean(w)                        ## Calculate sample mean of elements in w
## [1] 1.904663
sd(w)                           ## Calculate sample standard deviation of elements in w 
## [1] 3.241142
## b. 
par(mfrow=c(1,3))
plot(x = x, y = w, main = "X vs. W", 
     cex.lab = 2, cex.axis = 2, cex.main = 2)
abline(h = 0)                 ##add the horizontal line of zero     

plot(x = y, y = w, main = "Y vs. W", 
     cex.lab = 2, cex.axis = 2, cex.main = 2)
abline(h = 0)
   
plot(x = z, y = w,  main = "Z vs. W", 
     cex.lab = 2, cex.axis = 2, cex.main = 2)
abline(h = 0)

## c. 
par(mfrow = c(1,1))
plot(x = 2*x + 1.5*y, y = w,  main = "2X + 1.5Y vs. W", 
     cex.lab = 2, cex.axis = 2, cex.main = 2)
abline(a = 0.3, b = 1)