r - 线性回归预测:没有适用于“预测”的方法应用于“data.Frame”类的对象
问题描述
我有我的数据(当前是虚拟数据):
data_for_prediction <- original_data[,c(1,3)]
如果您想重现问题,则以下内容足以解决此错误:
data_for_prediction <- data.frame(
diff = c(1,2,3),
f.mean_slope = c (1,2,3)
)
其中仅包含两行:“diff”(Y)和“f.mean_slope”(x)
然后我对整个事情进行采样:
set.seed(101)
trainingRowIndex <- sample(1:nrow(data_for_prediction), 0.8*nrow(data_for_prediction))
trainingData <- data_for_prediction[trainingRowIndex, ]
testData <- data_for_prediction[-trainingRowIndex, ]
之后,我创建了一个拟合:
model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")
当我现在尝试预测一些事情时:
newdata <- data.frame(
f.mean_slope = c(1,2,3)
)
distPred <- predict(model_fit, newdata)
然后 R Studio 只返回错误消息:
UseMethod(“predict”)中的错误:没有适用于“predict”的适用方法应用于“data.Frame”类的对象
这让我发疯了,因为我已经搜索了大量的互联网问题,有一些类似的问题,但没有一个有效......
有人有想法吗?
解决方案
那是因为你使用了:
model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")
class(model_fit)
[1] "data.frame"
以上为您提供了用于拟合数据的模型矩阵。
您可以改为:
model_fit <- lm(diff ~ ., data = trainingData,model=TRUE)
newdata <- data.frame(
f.mean_slope = c(1,2,3)
)
distPred <- predict(model_fit, newdata)
模型矩阵可以在model_fit$model
推荐阅读
- powershell - 使用 yaml 文件和控制台在 Azure Pipelines 中使用 Appium 服务器执行
- javascript - CSS 模块在 react 16.13.1 中不起作用
- c# - 设置连接 ID 异常 Wpf
- python-3.x - 谁能解释一下代码的最后一行是如何工作的。python中使用的语言,我是python新手?
- python - 如何在视图中存储“ModelBase”对象列表(“ModelBase”对象不可下标)
- laravel - 视图命名空间上的 Laravel 视图组件支持
- java - 如何打印枚举描述
- c++ - cudaGraph:多线程流捕获仅在 cuda-memcheck 中运行时才会导致错误
- python - 更改 y 轴刻度 - FacetGrid
- python - 通过 pip 安装包时的入口点问题(来自其他包)