title: Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels
body: <p>I have the following code for minimizing the sum of deviation using optim() to find beta0 and beta1 but I am receiving the following errors I am not sure what I am doing wrong:</p>
  
  <pre><code>sum.abs.dev&lt;-function(beta=c(beta0,beta1),a,b)
  {
    total&lt;-0
    n&lt;-length(b)
    for (i in 1:n)
    {
      total &lt;- total + (b[i]-beta[1]-beta[2]*a[i])
    }
    return(total)
  }
  tlad &lt;- function(y = "farm", x = "land", data="FarmLandArea.csv")
  {
  
    dat &lt;- read.csv(data)
  
    #fit&lt;-lm(dat$farm~dat$land)
    fit&lt;-lm(y~x,data=dat)
    beta.out=optim(fit$coefficients,sum.abs.dev)
  
    return(beta.out)
  }
  </code></pre>
  
  <p>Here's the error and warnings are receive:</p>
  
  <pre><code>Error in `contrasts&lt;-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
    contrasts can be applied only to factors with 2 or more levels In addition: Warning message:
  In model.response(mf, "numeric") : NAs introduced by coercion
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/CCPgZ.png" alt="enter image description here"></p>