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 (eg 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
?
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.