A user wants to define a linear model and get the following error.how to fix that?

673    Asked by Deepalisingh in Data Science , Asked on Nov 20, 2019
Answered by Deepali singh

lm1 <- lm(predictorvariable ~ x1+x2+x3, data=dataframe.df)

The error is as follows.

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

To solve this, a data having 2 or more levels need to be considered. In this situation, the independent variable only with one class is considered. So this error occured.

(model <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris))

We get the following result


Now let us consider only one species and see the result

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris[iris$Species == "setosa", ]))

Now when we try to fit the model having only one class, this type of error occurs.

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : #contrasts can be applied only to factors with 2 or more levels

We can also check whether the variable is a factor or not by using

(l <- sapply(iris, function(x) is.factor(x)))




Your Answer

Interviews

Parent Categories