1

I'm trying to make a function that will run and compare a set of models given a dataset and a variable name (essentially to be able to change just one model set and have them apply to all relevant dependent variables--selecting an a priori modelset to compare rather than using a data-dredging existing function like glmulti). A simple example:

RunModelset<- function(dataset, response)
{
  m1 <- lm(formula=response ~ 1, data=dataset) 
  m2 <- lm(formula=response ~ 1 + temperature, data=dataset)
  comp <- AICctab(m1,m2, base = T, weights = T, nobs=length(data))
  return(comp)
}

If I manually enter a specific variable name within the function, it runs the models correctly. However, using the code above and entering a text value for the response argument doesn't work:

RunModel(dataset=MyData,response="responsevariablename") 

yields an error: invalid type (NULL) for variable 'dataset$response', which I interpret to mean it isn't finding the column I'm telling it to use. My problem must be in how R inserts a text value as an argument in the function.

How do I enter the response variable name so R knows that "formula=response ~" becomes "formula=dataset$responsevariablename ~"?

ETA Working answer based on this solution:

RunModel<- function(dataset, response)
{
 resvar <- eval(substitute(response),dataset)
 m1 <- lm(formula=resvar ~ 1, data=dataset) 
 m2 <- lm(formula=resvar ~ 1 + R.biomass, data=dataset)
 comp <- AICctab(m1,m2, base = T, weights = T, nobs=length(data))
 return(comp)
}

RunModel(dataset=MyData,response=responsevariablename)

NB - this didn't work when I had quotes on the response argument.

Community
  • 1
  • 1
Megachile
  • 11
  • 3

1 Answers1

0

You should be able to use match.call() to achieve this.

See this post

Community
  • 1
  • 1
lkq
  • 2,326
  • 1
  • 12
  • 22
  • I couldn't get match.call to work, but the eval(substitute()) [solution](http://stackoverflow.com/questions/19133980/passing-a-variable-name-to-a-function-in-r/19134129#19134129) posted on that question does the trick. Thanks! – Megachile Mar 14 '16 at 20:00
  • 2
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Bhargav Rao Mar 14 '16 at 20:12
  • Should I edit Keqiang's answer, provide one of my own or just paste my solution into a comment here? – Megachile Mar 14 '16 at 20:55