0

I have written the following code. I am extremely new to R. I don't have the knowledge of the language to debug this.

library(MASS)

RegressOnAll <- function() {
    li = list()
    nms = names(Boston)
    for (i in 2:length(nms)) {
        li[[i]] = lm(crim ~ nms[i], data=Boston)
    }
}

RegressOnAll()

An error message from the terminal

Error in model.frame.default(formula = crim ~ nms[i], data = Boston, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'nms[i]')
Calls: RegressOnAll ... lm -> eval -> eval -> <Anonymous> -> model.frame.default
Execution halted

I am not sure what to do with this error.

My goal is to pick out regression coefficients and compare them with multiple regression coefficients.

1 Answer 1

1

We can use reformulate

RegressOnAll <- function() {
    
    nms = setdiff(names(Boston), "crim")
    li <- vector('list', length(nms))
    for (i in seq_along(nms)) {
        li[[i]] = lm(reformulate(nms[i], response = "crim"), data=Boston)
    }
return(li)
}

-testing

> RegressOnAll()
[[1]]

Call:
lm(formula = reformulate(nms[i], response = "crim"), data = Boston)

Coefficients:
(Intercept)           zn  
    4.45369     -0.07393  


[[2]]

Call:
lm(formula = reformulate(nms[i], response = "crim"), data = Boston)

Coefficients:
(Intercept)        indus  
    -2.0637       0.5098  


[[3]]
...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.