1

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?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Kevin
  • 27
  • 1
  • 4
  • You may need `paste0("example ~", input1, " + ", input2)` and use `myregression("i1", "i2")` – akrun Apr 22 '19 at 04:36
  • 1
    Another approach assuming that `input1` and `input2` are character strings giving the names of columns in `trainData` is `lm(trainData[c("example", input1, input2)])` . – G. Grothendieck Apr 22 '19 at 04:39
  • Related: https://stackoverflow.com/q/46615693/6574038 – jay.sf Apr 22 '19 at 06:00

1 Answers1

1

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")
akrun
  • 874,273
  • 37
  • 540
  • 662