我有以下代码用于使用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
答案 0 :(得分:5)
这里有几个问题:
fit<-lm(y~x,data=dat)
)由R解释为fit<-lm("farm"~"land",data=dat)
。我会考虑以下内容:
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)