You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用tidyverse工具简化线性回归系数的批量计算?

用Tidyverse或矩阵乘法实现线性回归预测值计算

问题说明

我有一份包含变量名和对应系数的文件,需要用这些变量和系数构建线性回归公式,计算数据集的预测值。示例数据如下:

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添加新列y,效果等同于执行:

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

目前我手动写了包含约25个变量的公式,也能用循环实现,但想找更简洁的tidyverse工具实现方式,或者用矩阵向量乘法完成?循环实现的代码如下:

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] 
}

方法一:Tidyverse 简洁实现

利用dplyr的across和deframe函数,无需循环即可完成计算:

library(tidyverse)

# 提取截距和变量系数(转成命名向量)
intercept <- coefs %>% filter(varname == "(Intercept)") %>% pull(coef)
var_coefs <- coefs %>% filter(varname != "(Intercept)") %>% deframe()

# 生成预测列y
data %>%
  mutate(y = intercept + rowSums(across(all_of(names(var_coefs)), ~ .x * var_coefs[cur_column()])))

deframe()将变量名-系数的 tibble 转换为命名向量,across(all_of(...))遍历数据集中的目标变量,每个变量对应乘以系数后,用rowSums求和,最后加上截距得到预测值。

方法二:矩阵向量乘法实现

通过构造设计矩阵,用矩阵乘法直接计算,效率更高:

# 构造设计矩阵:添加全1的截距列,确保变量顺序和系数表一致
X <- cbind(1, data[, coefs$varname[coefs$varname != "(Intercept)"]])
# 提取系数向量(顺序与设计矩阵列对应)
beta <- coefs$coef

# 计算并添加预测列
data$y <- as.vector(X %*% beta)

设计矩阵第一列为全1,对应截距项,后续列是数据集中的自变量,系数向量的顺序和设计矩阵列完全匹配,矩阵乘法后转成向量即可得到每行的预测值。


内容的提问来源于stack exchange,提问作者qwr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 02:13:27