`对比< -`(`* tmp *`,value = contr.funs [1 + isOF [nn]])出错:对比只能应用于2级或更多级别的因子

时间:2014-05-01 18:55:08

标签: r function csv optimization regression

我有以下代码用于使用optim()来查找beta0和beta1来最小化偏差之和但是我收到以下错误我不确定我做错了什么:

sum.abs.dev<-function(beta=c(beta0,beta1),a,b)
{
  total<-0
  n<-length(b)
  for (i in 1:n)
  {
    total <- total + (b[i]-beta[1]-beta[2]*a[i])
  }
  return(total)
}
tlad <- function(y = "farm", x = "land", data="FarmLandArea.csv")
{

  dat <- read.csv(data)

  #fit<-lm(dat$farm~dat$land)
  fit<-lm(y~x,data=dat)
  beta.out=optim(fit$coefficients,sum.abs.dev)

  return(beta.out)
}

以下是错误和警告:

Error in `contrasts<-`(`*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

enter image description here

1 个答案:

答案 0 :(得分:5)

这里有几个问题:

  1. 您将变量指定为字符串,因此此行(fit<-lm(y~x,data=dat))由R解释为fit<-lm("farm"~"land",data=dat)
  2. 由于范围问题,更容易在函数中不指定默认变量。
  3. 我会考虑以下内容:

    tlad <- function(y, x){      
      fit <- lm(y~x)
      beta.out <- optim(fit$coefficients, sum.abs.dev)
      return(beta.out)
    }
    
    dat <- read.csv("FarmLandArea.csv")
    tlad(dat$farm, dat$land)
    
相关问题