Kevin
Kevin

Reputation: 27

How to use vars in lm in an own function?

I want to write a function, which calculates a linear regression based on the input.

I can build the function, but when I call it (e.g. myregression(i1,i2) it will result in an error)

myregression <- function(input1, input2) {
   model <- lm(data = trainData, example ~ input1 + input2)
}

How can I use the input in the function lm?

Upvotes: 1

Views: 57

Answers (1)

akrun
akrun

Reputation: 887048

Inside the function, we can use paste to create the formula

myregression <- function(input1, input2) {
    model <- lm(data = trainData, paste0("example ~", input1, " + ", input2))
     }

Or another option is reformulate

myregression <- function(input1, input2) {
      model <- lm(data = trainData, reformulate(c(input1, input2), "example"))
  }

and call the function as

myregression("i1", "i2")

Upvotes: 1

Related Questions