1. write a function which generates data from a linear model. Your function shou
ID: 3047908 • Letter: 1
Question
1. write a function which generates data from a linear model. Your function should accept three arguments: the number of observations, a vector of betas, and the standard deviation of the noise. The standard deviation should have a default value of 1. Your function should check that the standard deviation satisfies any necessary constraints. Check that beta has at least one entry. Each entry of the design matrix should be i.i.d.Uniform between -10 and 10. Your response vector must be equal to the beta vector times the design matrix plus mean zero, i.i.d. normal noise with the appropriate standard deviation. Your function must return a _data frame__. The first variable should be the response, namedy. The remaining columns should be named x1 through xp where p=length (betas). You may need to use the paste0 command to create the names for these columns. Try ?pasted for help. (Hint: Examine what happens when you create the data frame. You may not need to rename things if you're careful.)Explanation / Answer
Here you go :
linear_model = function(n, beta, sigma = 1){
if (length(beta) < 1)stop("beta cannot be empty")
if (sigma < 0)stop ("SD not non-negative")
epsilon = rnorm (n, 0, sigma)
X = t(sapply(1:n, function (i)runif (length(beta), -10,10)))
y = X %*% (beta) + epsilon
U = data.frame (y,X)
return(U)
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.