你在R中可能遇到的一个错误是:
Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) :
invalid type (list) for variable 'x'
这个错误通常发生在你试图在R中拟合一个回归模型或方差分析模型,并为其中一个变量使用一个列表而不是一个向量。
本教程分享如何在实践中修复这个错误。
如何重现该错误
假设我试图在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 ***
---
Signif. 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
---
Signif. 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中执行其他常见的操作。