[英]R Linear model predict function for many variables
I have a matrix of variables X
and fitted linear model Y ~ X1 + X2 + X3 + X4
.我有一个变量矩阵X
和拟合线性 model Y ~ X1 + X2 + X3 + X4
。 Let's say I want to predict Y
for a vector of means of my variables (X1_mean, X2_mean, X3_mean, X4_mean)
(and let's call it X_means
, I use function colMeans
).假设我想预测Y
的变量均值向量(X1_mean, X2_mean, X3_mean, X4_mean)
(我们称之为X_means
,我使用 function colMeans
)。 So, normally I'd do this in this fashion:所以,通常我会这样做:
predict(model, X1 = X1_mean, X2 = X2_mean, X3 = X3_mean, X4 = X4_mean)
But is there a faster way to do that?但是有没有更快的方法来做到这一点? For 4 variables typing (Xi = Xi_mean)
is not the end of the world, but for, let's say, 50 variables it will take a while.对于 4 个变量,键入(Xi = Xi_mean)
并不是世界末日,但是对于 50 个变量,这将需要一段时间。 Can I somehow rewrite it so as to assign each mean to each variable?我可以以某种方式重写它以便将每个平均值分配给每个变量吗? Something like colnames = means
. colnames = means
。
Let's say your data looks like this:假设您的数据如下所示:
set.seed(1)
df <- setNames(as.data.frame(matrix(rnorm(25), ncol=5)), c("Y", paste0("X", 1:4)))
df
#> Y X1 X2 X3 X4
#> 1 -0.6264538 -0.8204684 1.5117812 -0.04493361 0.91897737
#> 2 0.1836433 0.4874291 0.3898432 -0.01619026 0.78213630
#> 3 -0.8356286 0.7383247 -0.6212406 0.94383621 0.07456498
#> 4 1.5952808 0.5757814 -2.2146999 0.82122120 -1.98935170
#> 5 0.3295078 -0.3053884 1.1249309 0.59390132 0.61982575
And your model looks like this:你的 model 看起来像这样:
model1 <- lm(Y ~ X1 + X2 + X3 + X4, data = df)
Note that you can get a named list of the means of all your predictor columns like this:请注意,您可以获得所有预测变量列均值的命名列表,如下所示:
lapply(df[-1], mean)
#> $X1
#> [1] 0.1351357
#>
#> $X2
#> [1] 0.03812297
#>
#> $X3
#> [1] 0.459567
#>
#> $X4
#> [1] 0.08123054
So to predict at the mean of each predictor in this case we could just do:因此,在这种情况下,要预测每个预测变量的平均值,我们可以这样做:
predict(model1, lapply(df[-1], mean))
#> 1
#> 0.1292699
Created on 2020-12-08 by the reprex package (v0.3.0)由reprex package (v0.3.0) 于 2020 年 12 月 8 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.