首页 > 解决方案 > 使用 Dataframe of Coefficients 在 R 中进行测试集预测

问题描述

我目前有一个类似于以下的数据框:

coef_data
  x    y
1  -2 -0.1
2  -2 -0.1
3  -2 -0.1
4  -2 -0.1
5  -2 -0.1
6  -2 -0.1
7  -2 -0.1
8  -2 -0.1
9  -2 -0.1
10 -2 -0.1
11 -2 -0.1
12 -2 -0.1
13 -2 -0.1
14 -2 -0.1
15 -2 -0.1
16 -2 -0.1
17 -2 -0.1
18 -2 -0.1
19 -2 -0.1
20 -2 -0.1

其中xy对应于我的线性模型中的两个变量。我想将每一行用作给定测试集(我已包含在列表中)的预测。为了示例,我想使用第一行对以下数据框进行预测:

test_data <- data.frame(replicate(10, rnorm(20)))
colnames(test_data) <- c("ydot", "x", "y", "xx", "xy", "yy", "xxx", "xxy", "xyy", "yyy")

我知道您通常会开发一个线性模型并使用predict,但我在其他地方获得了系数。是否有替代方法:

predict(coef_data[1, ], test_data)

由于使用预测功能会给我:

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "data.frame"

编辑:我已经能够手动做到这一点:

ydot_prediction <- sqrt(sum(test_data[, 1, drop = FALSE] -
  (coef_data[, 1] * test_data[, 2, drop = FALSE] +
     coef_data[, 2] * test_data[, 3, drop = FALSE])) ^ 2)

但是,我希望能够自动执行此操作。因此,从数据框中提取与test_data数据框中的列名称相同的列coef_data

提前致谢。

标签: rpredict

解决方案


我认为您正在尝试做这样的事情

set.seed(2021)
test_data <- data.frame(x=rnorm(7), y=rnorm(7))
test_data$xx <- test_data$x * test_data$x 
test_data$xy <- test_data$x * test_data$y
print(test_data) 
#            x           y         xx           xy
# 1 -0.1224600  0.91556637 0.01499645 -0.112120244
# 2  0.5524566  0.01377194 0.30520833  0.007608399
# 3  0.3486495  1.72996316 0.12155648  0.603150795
# 4  0.3596322 -1.08220485 0.12933535 -0.389195760
# 5  0.8980537 -0.27282518 0.80650043 -0.245011659
# 6 -1.9225695  0.18199540 3.69627356 -0.349898808
# 7  0.2617444  1.50854179 0.06851011  0.394852311

coeff <- c(x=-2, y=-1, xx=+3, xy=+2, constant=+7)
predictions <- as.matrix(cbind(test_data,1)) %*% coeff
print(predictions)
#           [,1]
# [1,]  6.150102
# [2,]  6.812157
# [3,]  6.143709
# [4,]  6.972555
# [5,]  7.406196
# [6,] 21.052167
# [7,]  5.963204

-2*-0.1224600 -1*0.91556637 +3*0.01499645 +2*-0.112120244 +7在哪里6.150102


推荐阅读