title: How to pass a formula as an argument to a function in r?
body: <p>How do I pass a formula as an argument in R?</p>
  
  <p>The code below works for the first two cases, but when I pass in the formula, I get an error:  <code>Error in model.frame.default(formula = formula, weights = weights, na.action = na.omit,  :   invalid type (closure) for variable '(weights)'</code></p>
  
  <pre class="lang-r prettyprint-override"><code>makeModel&lt;-function(formula,weights) {
      m &lt;- lm(formula, na.action = na.omit, weights = weights)
      return(m);
  }
  run&lt;-function(t) {
      f&lt;-formula(t$y~t$x+t$r)
      m &lt;- lm(t$y~t$x+t$r, na.action = na.omit, weights = t$size)
      m &lt;- lm(f, na.action = na.omit, weights = t$size)
      m &lt;- makeModels(f,t$size)    
  }
  l&lt;-20
  x&lt;-seq(0,1,1/l)
  y&lt;-sqrt(x)
  r=round(runif(n=length(x),min=0,max=.8))
  n&lt;-1:(l+1)
  size=n/sum(n)
  t&lt;-data.frame(x,y,r,n,size)
  run(t)
  </code></pre>
  
  <p>edit 1: this code: </p>
  
  <pre><code>makeModel&lt;-function(formula,weights,t) {
      print(class(weights))
      m &lt;- lm(formula, na.action = na.omit, weights = weights,data=t)
      return(m);
  }
  run&lt;-function(t) {
      f&lt;-formula(y~x+r)
      f &lt;- as.formula("t$y~t$x+t$r")
      m &lt;- lm(y~x+r, na.action = na.omit, weights = t$size,data=t)
      m &lt;- lm(f, na.action = na.omit, weights = t$size,data=t)
      m &lt;- makeModel(f,t$size,t)    
  }
  </code></pre>
  
  <p>produces:</p>
  
  <p>Error in model.frame.default(formula = formula, data = t, weights = weights,  : 
    invalid type (closure) for variable '(weights)' </p>
  
  <p>edit 2: works:</p>
  
  <pre><code>makeModel &lt;- function(formula, data) {
      # size is looked in data first, which is why this works
      m &lt;- lm(formula, na.action = na.omit, weights = size, data =  data) # works
      #m &lt;- lm(formula, na.action = na.omit, weights = data$size, data =  data) # fails!
      return(m)
  }
  </code></pre>
  
  <p>r is strange!</p>
  
  <p>Does anyone know why the line with: weights=data$size fails?</p>
  
  <p>Edit 3: Got: weights=data$size to work.</p>
  
  <pre><code>makeModel&lt;-function(formula,w,data) {
      print(class(weights))
      m &lt;- lm(formula, na.action = na.omit, weights = size, data =  data) # works
      m &lt;- lm(formula, na.action = na.omit, weights = data$size, data =  data) #works
      m &lt;- lm(formula, na.action = na.omit, weights = w,data=data) # fails
      return(m);
  }
  run&lt;-function(data) {
      f&lt;-formula(y~x+r)
      #f &lt;- as.formula("t$y~t$x+t$r")
      m &lt;- lm(y~x+r, na.action = na.omit, weights = data$size,data=data)
      m &lt;- lm(f, na.action = na.omit, weights = data$size,data=data)
      m &lt;- makeModel(f,data$size,data)    
  }
  </code></pre>
  
  <p>The last one fails with a:  Error in eval(extras, data, env) : object 'w' not found</p>