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

Julia中按组执行线性回归及获取统计指标的实现方法

在Julia中按组执行线性回归并提取统计量

要针对分组数据集分别执行线性回归并获取p值、R平方等统计量,可借助DataFrames的分组功能和GLM包的回归工具实现,步骤如下:

1. 加载所需包与数据集

首先导入必要的包,并加载你的分组数据集:

using DataFrames
using GLM

# 加载分组数据集
df = DataFrame(
    group = ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
             'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'],
    x = [2,3,2,1,3,5,7,4,2,3,4,5,2,6,3,1,6,1],
    y = [2,3,5,1,5,6,4,2,3,3,2,4,7,1,8,4,3,1]
)

2. 定义统计量提取函数

编写一个函数,输入单个分组的子数据集,执行线性回归并返回所需的统计量(系数、p值、R平方等):

function get_regression_stats(subdf)
    # 拟合线性回归模型
    model = lm(@formula(y ~ x), subdf)
    # 获取系数表(包含p值等信息)
    coef_table = coeftable(model)
    
    # 提取截距和x的系数、p值
    intercept_coef = coef_table.coefs[1, 1]
    intercept_pval = coef_table.coefs[1, 4]
    x_coef = coef_table.coefs[2, 1]
    x_pval = coef_table.coefs[2, 4]
    
    # 提取R平方和调整后R平方
    r_squared = r2(model)
    adj_r_squared = adjr2(model)
    
    # 返回结构化结果
    return DataFrame(
        intercept_coef = intercept_coef,
        intercept_pval = intercept_pval,
        x_coef = x_coef,
        x_pval = x_pval,
        r_squared = r_squared,
        adj_r_squared = adj_r_squared
    )
end

3. 按组执行回归并汇总结果

使用groupby按group列分组,再用combine对每个分组应用上述函数,得到汇总的统计结果:

grouped_results = combine(groupby(df, :group), get_regression_stats)

输出结果示例

运行后会得到包含每组统计量的DataFrame:

2×7 DataFrame
 Row │ group  intercept_coef  intercept_pval  x_coef   x_pval   r_squared  adj_r_squared
     │ Char   Float64         Float64         Float64  Float64  Float64    Float64
─────┼───────────────────────────────────────────────────────────────────────────────────
   1 │ A          2.14516         0.0951028    0.403226  0.225419  0.197183     0.0968703
   2 │ B          5.30909         0.00106737  -0.563636  0.0476703  0.382682     0.292016

补充:直接查看每组的完整模型

如果需要查看每组回归的完整输出(如系数表、模型信息),可以先分组再逐个拟合模型:

# 分组
grouped_data = groupby(df, :group)
# 对每个分组拟合模型
group_models = map(subdf -> lm(@formula(y ~ x), subdf), grouped_data)

# 查看A组的完整模型结果
println(group_models[1])
# 查看B组的完整模型结果
println(group_models[2])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:31:02