In: Math
use R
# Problem 4 (5 pts each):
# Set x as a vector of 500 random numbers from Unif(100,300).
# This vector will be kept fixed for the rest of this
problem.
#
# (a) Define a function b1(x, beta0, beta1, sigm) that uses the
lm() function to
# return the regression line slope b1 for y as a linear function of
x, where
#
# y = beta0 + beta1 x + err
#
# and the error term 'err' has a normal N(0,sigm^2)
distribution
# (note that standard deviation is equal 'sigm').
#
# Hint: See how the slope b1 is extracted in the initial example of
Session 11.
# (b) Replicate the function b1 twenty thousand times for
# beta0 = 15, beta1 = 2, and sigm =10, and store into a vector
'Slopes'.
# (c) Plot the empirical density of Slopes.
# (d) Calculate sample mean and sample variance of Slopes.
# (e) Add to the plot the pdf of a Normal distribution with
parameters from part (d).
The R code is given below for the problem
#----------------------R code----------------------
rm(list=ls(all=T))
n=500;beta0=15;beta1=2;sigm=10
set.seed(10)
x=runif(n,100,300) ## Generating vector x form Uniform(100,300)
b1=function(x,beta0,beta1,sigm){ ##defining function b1
err=rnorm(n,0,sigm) ###generating values on err from
Norm(0,sigm^2)
y=beta0+beta1*x+err ###generating values on y
b=as.vector(lm(y~x)$coeff) ###fitting the linear regression line
y=beta0+beta1+err
b ##vector of slopes
}
b1(x,beta0,beta1,sigm)
Slopes=replicate(20,b1(x,beta0,beta1,sigm)) ###Replicating the function b1 20,000 times and storing to Slopes
m=apply(Slopes,1,mean) ##sample mean of the slopes
### m[1] is mean of beta0 samples and m[2] is mean of beta1
samples
s=apply(Slopes,1,var) ##sample variance of the slopes
### s[1] is sample variance of beta0 and s[2] is sample variance of
beta1
plot(density(Slopes[1,]),ylim=c(0,0.32),main="Empirical
Density") ###empirical density plot of beta0
curve(dnorm(x,m[1],sqrt(s[1])),col="red",add=T) ##adding plot of
Norm(m[1],s[1])
plot(density(Slopes[2,]),ylim=c(0,60),main="Empirical Density")
###empirical density plot of beta1
curve(dnorm(x,m[2],sqrt(s[2])),col="green",add=T) ##adding plot of
Norm(m[2],s[2])