How do you loop through a regression?

I am trying to loop through a regression but am having issues. Here is my reproducible data:

data(iris)

  model1 <- lm(Sepal.Length ~ Sepal.Width, data=iris1)
  model2 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=iris1)

predict1 <- function(value, model){ 
  y = model$coefficients[1] + (model$coefficients[-1]%*% value)
  return (y)
}

predict2 <- function(values, model){
  y = model$coefficients[1] + (model$coefficients[-1]%*% values)
  return (y)
}

n = 300

for (i in 1:n){
  
  iris1 <- iris[sample(1:nrow(iris), 50, replace = TRUE),]

## I suspect there is something wrong here, but I am not sure what the issue is...
  
  model1[[i]] <- lm(Sepal.Length ~ Sepal.Width, data=iris1)
  model2[[i]] <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=iris1)
  
  predictions1 <- predict1(iris1$Sepal.Width[[i]], model1[[i]])
  values <- c(iris1$Sepal.Width, iris1$Petal.Length, iris1$Petal.Width)
  predictions2 <- predict2(values[[i]], model2[[i]])
}

Great reprex!

Two things pop out.

n <- ????

model1[[i]] <- ... modifies model1, but it doesn't exist.

1 Like

I just edited the code and defined n and model1 and model2.

Sorry but your code doesn't make sense and is not clear what you are trying to accomplish. Is this close to what you are trying to do?

n = 300
predictions1 <- double()
predictions2 <- double()

for (i in 1:n){
    
    iris1 <- iris[sample(1:nrow(iris), 50, replace = TRUE),]
    
    model1 <- lm(Sepal.Length ~ Sepal.Width, data=iris1)
    model2 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=iris1)
    
    predictions1 <- c(predictions1, predict(model1, newdata = iris1))
    predictions2 <- c(predictions2, predict(model2, newdata = iris1))
}

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.