Edi Itelman
Edi Itelman

Reputation: 443

build a model within a function returns "variable lengths differ (found for 'var')"

I am trying to build a function to run a model based on a list of variables. The code works fine outside a function

data <- ovarian
model <- glm(fustat ~ rx, family = binomial(), data = data)
odds.ratio(model)

but when I try to do this in a function it returns an error

OR <- function(var){
  model <- glm(fustat ~ var, family = binomial(), data = data)
  return(odds.ratio(model))
}
OR("rx")

 Error in model.frame.default(formula = fustat ~ var, data = data, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'var') 

Any idea how to get around this?

Thanks

Upvotes: 0

Views: 33

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

You are passing string as input to the function, convert it into formula or something which can be coerced to a formula. One way would be to use reformulate.

OR <- function(var){
  model <- glm(reformulate(var, "fustat"), family = binomial(), data = data)
  return(odds.ratio(model))
}

OR("rx")

Upvotes: 1

Related Questions