Search code examples
rmappingevallapply

Can I fit different regression models using mapply?


I'm trying to see if I can fit multiple regression models using the mapply function on the iris dataset.

I start by defining my regression model:

reg<-function(dependent,independent){lm(eval(paste0(dependent,"~",independent,",data=iris")))}

I then define my vectors of dependent and independent variables:

dependent<-c("Sepal.Length","Sepal.Width")
independent<-c("Sepal.Width","Sepal.Length")

Finally I try to apply the mapply function:

models_reg<-mapply(reg,dependent,independent)

I get an error message, however, claiming that:

Error in parse(text = x, keep.source = FALSE) : 
  <text>:1:25: unexpected ','
1: Sepal.Length~Sepal.Width,

Is it possible to achieve my objective (fitting different regression models using mapply) and in that case, what am I doing wrong?


Solution

  • You don't need to evaluate a string here. You can pass formula as string in lm :

    reg<- function(dependent,independent) {
       lm(paste0(dependent,"~",independent),data=iris)
    }
    

    Another way to construct the formula is using reformulate :

    reg<-function(dependent,independent) {
      lm(reformulate(independent, dependent),data=iris)
    }
    

    Now you can call using Map :

    Map(reg, dependent, independent)
    
    #$Sepal.Length
    
    #Call:
    #lm(formula = reformulate(independent, dependent), data = iris)
    
    #Coefficients:
    #(Intercept)  Sepal.Width  
    #     6.5262      -0.2234  
    
    
    #$Sepal.Width
    
    #Call:
    #lm(formula = reformulate(independent, dependent), data = iris)
    
    #Coefficients:
    # (Intercept)  Sepal.Length  
    #     3.41895      -0.06188