R

[R오류] contrasts can be applied only to factors with 2 or more levels

excelsu 2022. 6. 30. 14:39

회귀분석을 진행하다가 

lm(rawdata$qwe~., data=rawdata)

를 실행했는데 

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

오류가 떴다.

원인은 여러가지가 있는데

한컬럼의 데이터가 전부 같을때 발생한다.

전부 같은데이터인지 확인하기 위해서는 

values_count <- sapply(lapply(data, unique), length)  # Identify variables with 1 value
values_count

lm(y ~ ., data[ , values_count > 1])

으로 확인해 보면 된다.

 

그래도 해결이 안된다면 na값이 있을때 발생하는 오류이기때문에 na값을 채워주거나 행을 삭제하고 실행하면 된다..

 

참고 : https://statisticsglobe.com/r-error-contrasts-applied-to-factors-with-more-levels 

 

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

How to solve the error message "contrasts can be applied only to factors with 2 or more levels" in R - Programming examples & code in RStudio

statisticsglobe.com