R Error in Contrasts: Applied Only to Factors with More Levels (2 Examples)

In this R programming tutorial you’ll learn how to deal with the error “contrasts can be applied only to factors with 2 or more levels”.

Creation of Example Data

my_df <- data.frame(col1 = c(7, 2, 5, 3, 3, 1, 5),  # Creating data frame in R
                    col2 = c(6, 1, 3, 5, 5, 1, 2),
                    col3 = as.factor(c("A", "A", "B", "B", "A", "C", "A")),
                    col4 = as.factor(5),
                    outcome = c(1, 6, 9, 1, 1, 2, 7))
my_df                                               # Showing example data in RStudio
#   col1 col2 col3 col4 outcome
# 1    7    6    A    5       1
# 2    2    1    A    5       6
# 3    5    3    B    5       9
# 4    3    5    B    5       1
# 5    3    5    A    5       1
# 6    1    1    C    5       2
# 7    5    2    A    5       7

Example 1: Replicating the Error Message: contrasts can be applied only to factors with 2 or more levels

lm(outcome ~ col1 + col2 + col3 + col4,             # Error when applying lm() function
   my_df)
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
#   contrasts can be applied only to factors with 2 or more levels

Example 2: Solving the Error Message: contrasts can be applied only to factors with 2 or more levels

lm(outcome ~ col1 + col2 + col3,                    # Removing col4 (only one value) from model
   my_df)
# Call:
# lm(formula = outcome ~ col1 + col2 + col3, data = my_df)
# 
# Coefficients:
# (Intercept)         col1         col2        col3B        col3C  
#      6.5019       0.9351      -1.9218       2.4447      -3.5153

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top