Juan M Gutierrez
Juan M Gutierrez

Reputation: 11

R Functions: how to pass a response variable as a parameter?

When I use functions such as glm I need to specify the explicit formula, for example:

glm(sales ~ ., data = database)

However, when I use this inside of a function, the response variable isn't always "sales". Is there any way I can make the formula parameter of the glm function "dynamic" in order to address this issue?

Upvotes: 1

Views: 262

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76653

Something like the following?

dynamic <- function(database, response){
    fmla <- as.formula(paste(response, ".", sep = "~"))
    glm(fmla, data = database)
}

Then call with the data.frame and response variable of your choice.

Upvotes: 3

Related Questions