第20行出现问题:x3 <- lm(Salary ~ ...
as.data.frame.default(data)中的错误:无法将类“ c(“ train”,“ train.formula”)'强制转换为data.frame
如何解决?
attach(Hitters)
Hitters
library(caret)
set.seed(123)
# Define training control
set.seed(123)
train.control <- trainControl(method = "cv", number = 10)
# Train the model
x2 <- train(Salary ~., data = x, method = "lm",
trControl = train.control)
# Summarize the results
print(x)
x3 <- lm(Salary ~ poly(AtBat,3) + poly(Hits,3) + poly(Walks,3) + poly(CRuns,3) + poly(CWalks,3) + poly(PutOuts,3), data = x2)
summary(x3)
MSE = mean(x3$residuals^2)
print("Mean Squared Error: ")
print(MSE)
答案 0 :(得分:0)
首先,如@dcarlson所述,您应该定义x。 其次,x3不返回数据帧。 如果您运行
str(x2)
您将看到lm函数中使用的所有元素都是称为trainingData的数据框的一部分。 因此,如果您打算使用lm函数,请将其用作lm函数中的数据源,不 x2。 我已经在下面重写了您的代码。
PS我距离R专家还很远,所以如果有人想用这个答案射击,那就继续吧,我总是愿意学习;)
attach(Hitters)
Hitters
library(caret)
set.seed(123)
# Define training control
set.seed(123)
train.control <- trainControl(method = "cv", number = 10)
# Train the model
x2 <- train(Salary ~., data = x, method = "lm", trControl = train.control)
# Summarize the results
print(x2)
# str(x2) # $trainingData data.frame
x2$trainingData[["AtBat"]]
m <- x2$trainingData
x3 <- lm(Salary ~ poly(AtBat,3) + poly(Hits,3) + poly(Walks,3) + poly(CRuns,3) + poly(CWalks,3) + poly(PutOuts,3), data = m)
summary(x3)
MSE = mean(x3$residuals^2)
cat("Mean Squared Error: ", MSE) # use cat to concatenate text and variable value in one line