如何从brm()拟合结果中无硬编码提取mu、hu、shape后验估计
解决方案
方法1:利用模型内置的前缀属性
brms模型对象会自动存储当前使用的固定效应前缀(默认是b_,可通过brm()的prefix参数修改),直接读取该前缀构建匹配规则,彻底避免硬编码:
# 获取模型的固定效应前缀 prefix <- fit_hnb2$prefix # 提取mu(count公式)的所有固定效应后验样本 count_para <- as.data.frame(fit_hnb2, variable = paste0("^", prefix, "mu_"), regex = TRUE) # 提取hu(zero公式)的所有固定效应后验样本 hu_para <- as.data.frame(fit_hnb2, variable = paste0("^", prefix, "hu_"), regex = TRUE) # 提取shape(shape公式)的所有固定效应后验样本 shape_para <- as.data.frame(fit_hnb2, variable = paste0("^", prefix, "shape_"), regex = TRUE)
方法2:先筛选参数名再提取(更灵活)
如果需要对参数名做额外处理,可先获取所有参数名,再结合前缀筛选目标参数:
# 获取模型所有参数的名称 all_pars <- variables(fit_hnb2) # 筛选mu组件的固定效应参数 mu_pars <- grep(paste0("^", fit_hnb2$prefix, "mu_"), all_pars, value = TRUE) count_para <- as.data.frame(fit_hnb2, variable = mu_pars) # 筛选hu组件的固定效应参数 hu_pars <- grep(paste0("^", fit_hnb2$prefix, "hu_"), all_pars, value = TRUE) hu_para <- as.data.frame(fit_hnb2, variable = hu_pars) # 筛选shape组件的固定效应参数 shape_pars <- grep(paste0("^", fit_hnb2$prefix, "shape_"), all_pars, value = TRUE) shape_para <- as.data.frame(fit_hnb2, variable = shape_pars)
关键优势
两种方法都依赖模型自带的prefix属性,无论你将前缀修改为beta_或其他值,代码都能自动适配,无需手动调整正则表达式。方法1更简洁直接,方法2适合需要对参数名做二次处理的场景。
内容的提问来源于stack exchange,提问作者Dananji
相关产品推荐
相关产品推荐

