In: Math
Use R to generate n = 400 samples (idependent identically distributed random numbers) of X ∼ N(0, 4). For each Xi , simulate Yi according to Yi = 3 + 2.5Xi + εi , where εi ∼ N(0, 16), i = 1, ..., n. Use R to solve the following questions. (a) Compute the least square estimators of βˆ 0 and βˆ 1. (b) Draw a regression line according to the numbers computed in (a). Plot Y and X with this regression line. Hint: Use rnorm.
R code with comments
#set the random seed
set.seed(123)
#set the sample size
n<-400
#generate X
x<-rnorm(n,mean=0,sd=sqrt(4))
#generate epsilon
e<-rnorm(n,mean=0,sd=sqrt(16))
#simulate Y
y<-3+2.5*x+e
#a) compute the least square estimators
fit<-lm(y~x)
summary(fit)
sprintf('The estimated value of the intercept (βˆ0) is
%.4f',fit$coef[1])
sprintf('The estimated value of the slope (βˆ1) is
%.4f',fit$coef[2])
#b) plot x,y and the regression line
plot(x,y,main="Y vs X")
abline(fit,col="red")
# get this
get this plot