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:
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)
}
Here's the error and warnings are receive:
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
This error occurs when you attempt to fit a regression model using a predictor variable that is either a factor or character and only has one unique value.
In R, factors are used to work with categorical variables, variables that have a fixed and known set of possible values. They are also useful when you want to display character vectors in a non-alphabetical order. Historically, factors were much easier to work with than characters.
There are several problems here:
fit<-lm(y~x,data=dat)
) is interpreted by R as fit<-lm("farm"~"land",data=dat)
.I would consider the following instead:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With