How to fix this error:

Note that we can use the sapply() and lapply() functions together to count the number of unique values present in each of the predictor variables.

Example:

Here, Using lapply() function we can even print the values present in the individual predictor variables.

R




# Create a data frame
dataframe <- data.frame(parameter1=c(8, 1, 13, 24, 9),
                 parameter2=as.factor(6),
                 parameter3=c(17, 9, 18, 13, 12),
                 parameter4=c(12, 21, 32, 4, 19))
  
# Find the unique values for each variable
sapply(lapply(dataframe, unique), length)


Output:

Output

Example:

Now from the below code, we can see that parameter2 contains only one unique value. Hence, we can fix this error by simply removing parameter2 from the regression model.

R




# Create a data frame
dataframe <- data.frame(parameter1=c(8, 1, 13, 24, 9),
                 parameter2=as.factor(6),
                 parameter3=c(17, 9, 18, 13, 12),
                 parameter4=c(12, 21, 32, 4, 19))
  
# Find the unique values for each variable
lapply(dataframe[c('parameter1', 'parameter2',
                   'parameter3', 'parameter4')], 
       unique)


Output:

Example:

Hence, by removing parameter2, the program compiled successfully without any error.

R




# Create a data frame
dataframe <- data.frame(parameter1=c(8, 1, 13, 24, 9),
                 parameter2=as.factor(6),
                 parameter3=c(17, 9, 18, 13, 12),
                 parameter4=c(12, 21, 32, 4, 19))
  
# Fit regression model using all the predictor variables
# except parameter2
model <- lm(parameter4 ~ parameter1 + parameter3, data=dataframe)
  
# Display model summary
summary(model)


Output:



How to Fix in R: Contrasts can be applied only to factors with 2 or more levels.

In this article, we will discuss how we can fix “contrasts can be applied only to factors with 2 or more levels” error in the R programming language.

Contrasts can be applied only to factors with 2 or more levels:

It is a common error produced by the R compiler. The complete form of this error is given below:

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 

  contrasts can be applied only to factors with 2 or more levels

Such an error is produced by the R compiler when we try to fit a regression model with the help of the predictor variable that is either a character or factor and contains only one unique value.

Similar Reads

When this error might occur:

R # Create a data frame dataframe <- data.frame(parameter1=c(8, 1, 13, 24, 9),                  parameter2=as.factor(6),                  parameter3=c(17, 9, 18, 13, 12),                  parameter4=c(12, 21, 32, 4, 19))    # Print the dataframe dataframe...

How to fix this error:

...

Contact Us