Reputation: 27
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
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