使用表中的线性回归系数来计算值

问题描述 投票:0回答:1

我有一个包含许多变量名称和系数的文件。任务是使用这些变量名称和系数创建线性回归公式并将其应用于数据。这是一个小例子:

coefs <- tibble(varname = c("(Intercept)", "dxaids", "abnormal_bun"),
                coef = c(-3.1, 0.1, 0.2))

data <- tibble(dxaids = c(0,0,1), abnormal_bun = c(1,0,0))

目标是有效地创建一个新专栏

data %>% mutate(y = -3.1 + 0.1 * dxaids + 0.2 * abnormal_bun)

我暂时所做的是手动写出大约有 25 个变量的方程。

当然,我可以为此编写一个丑陋的循环,如下所示,但是使用 tidyverse 工具有没有更干净的方法?也许这可以通过单个矩阵向量乘法来完成,但 dplyr 似乎不适合矩阵运算。

y <- as.numeric(coefs[coefs$varname == "(Intercept)", "coef"])

for (i in 1:nrow(coefs)) {
  varname <- as.character(coefs[i,"varname"])
  coef <- as.numeric(coefs[i,"coef"])
  if (varname != "(Intercept)") 
    y <- y + coef * data[,varname] 
}
r tidyverse linear-regression coefficients
1个回答
0
投票

如果使用矩阵乘法,则可以避免使用

for
循环:

coefs$coef[1] + (as.matrix(data) %*% coefs$coef[-1])
     [,1]
[1,] -2.9
[2,] -3.1
[3,] -3.0

只需确保

data
中的列与
coefs$coef[-1]

中的顺序相对应
© www.soinside.com 2019 - 2024. All rights reserved.