1

I have written my function for MLR. However, there seems to an issue with output (see examples in the end).

But when I run the code, line by line, the output is correct.

mlr <- function(dependentvar, dataset) {

x <- model.matrix(dependentvar ~., dataset) # Design Matrix for x

y <- dependentvar # dependent variable

betas <- solve(crossprod(x))%*%crossprod(x,y) # beta values

SST <- t(y)%*%y - (sum(y)^2/dim(dataset)[1]) # total sum of squares

SSres <- t(y)%*%y -(t(betas)%*%crossprod(x,y))  # sum of squares of residuals

SSreg <- SST - SSres  # regression sum of squares

sigmasqr <- SSres/(length(y) - dim(dataset)[2])  # variance or (MSE)

varofbeta <- sigmasqr[1]*solve( crossprod(x)) # variance of beta

cat("SST:", SST,"SSresiduals:", SSres,"SSregression:", SSreg, sep = "\n", append = FALSE)

return(betas)

}

To see the problem, try

mlr(trees$Height, trees)

I get the same problem even if I get rid of $

Height <- trees$Height
mlr(Height, trees)
0

1 Answer 1

1

Use the following:

x <- model.matrix(reformulate(".", dependentvar), dataset)
y <- dataset[[dependentvar]]

and pass in dependentvar as a string.

Example:

mlr("Height", trees)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.