R에서 수정하는 방법: 변수에 대한 잘못된 유형(목록)


R에서 발생할 수 있는 오류는 다음과 같습니다.

 Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE): 
  invalid type (list) for variable 'x' 

이 오류는 일반적으로 R에서 회귀 모델이나 ANOVA 모델을 적합시키고 벡터 대신 변수 중 하나에 대한 목록을 사용하려고 할 때 발생합니다.

이 튜토리얼에서는 실제로 이 오류를 수정하는 방법을 설명합니다.

오류를 재현하는 방법

R에 간단한 선형 회귀 모델을 맞추려고 한다고 가정해 보겠습니다.

 #define variables
x <- list(1, 4, 4, 5, 7, 8, 9, 10, 13, 14)
y <- c(10, 13, 13, 14, 18, 20, 22, 24, 29, 31)

#attempt to fit regression model
model <- lm(y ~ x)

Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE): 
  invalid type (list) for variable 'x'

lm() 함수는 벡터만 입력으로 사용할 수 있고 변수 x는 현재 목록이기 때문에 오류가 발생합니다.

오류를 방지하는 방법

이 오류를 피하는 가장 쉬운 방법은 unlist() 함수를 사용하여 목록 변수를 벡터로 변환하는 것입니다.

 #define variables
x <- list(1, 4, 4, 5, 7, 8, 9, 10, 13, 14)
y <- c(10, 13, 13, 14, 18, 20, 22, 24, 29, 31)

#attempt to fit regression model
model <- lm(y ~ unlist(x))

#view the model output
summary(model)

Call:
lm(formula = y ~ unlist(x))

Residuals:
    Min 1Q Median 3Q Max 
-1.1282 -0.4194 -0.1087 0.2966 1.7068 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 6.58447 0.55413 11.88 2.31e-06 ***
unlist(x) 1.70874 0.06544 26.11 4.97e-09 ***
---
Significant. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8134 on 8 degrees of freedom
Multiple R-squared: 0.9884, Adjusted R-squared: 0.987 
F-statistic: 681.8 on 1 and 8 DF, p-value: 4.97e-09

이번에는 unlist()를 사용하여 변수 x를 벡터로 변환했기 때문에 오류 없이 단순 선형 회귀 모델을 적합할 수 있다는 점에 유의하세요.

다중 선형 회귀 모델을 피팅하고 현재 목록 개체인 예측 변수가 여러 개 있는 경우 회귀 모델을 피팅하기 전에 unlist()를 사용하여 각 변수를 벡터로 변환할 수 있습니다.

 #define variables
x1 <- list(1, 4, 4, 5, 7, 8, 9, 10, 13, 14)
x2 <- list(20, 16, 16, 15, 16, 12, 10, 8, 8, 4)
y <- c(10, 13, 13, 14, 18, 20, 22, 24, 29, 31)

#fit multiple linear regression model
model <- lm(y ~ unlist(x1) + unlist(x2))

#view the model output
summary(model)

Call:
lm(formula = y ~ unlist(x1) + unlist(x2))

Residuals:
    Min 1Q Median 3Q Max 
-1.1579 -0.4211 -0.1386 0.3108 1.7130 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 8.34282 4.44971 1.875 0.102932    
unlist(x1) 1.61339 0.24899 6.480 0.000341 ***
unlist(x2) -0.08346 0.20937 -0.399 0.702044    
---
Significant. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8599 on 7 degrees of freedom
Multiple R-squared: 0.9887, Adjusted R-squared: 0.9854 
F-statistic: 305.1 on 2 and 7 DF, p-value: 1.553e-07

다시 말하지만, 목록의 각 객체를 벡터로 변환했기 때문에 오류가 발생하지 않습니다.

추가 리소스

다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

R에서 glm 출력을 해석하는 방법
R에서 ANOVA 결과를 해석하는 방법
R 경고 처리 방법: glm.fit: 알고리즘이 수렴되지 않았습니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다