为了保证输出结果的一致性,我将MASS::polr()放进了一个函数,然后对输出的结果进行了一定的调整。log报错说:错误于eval(expr, p): 找不到对象'f_str'。“模型拟合完成”也被print在了log窗口里,貌似是broom::tidy的问题,请问这个错误的原因是什么以及怎么解决?
model_ordinal_regression <- function(data, y, x, f_x=NA, digits_coef=3, digits_p=3) {
# Piece up the function
if(is.na(f_x)){
f_str <- paste("`", y, "` ~ `", paste(x, collapse = "` + `"), "`", sep="")
}else{
f_str <- paste("`", y, "` ~ ", f_x, sep="")
}
# Modeling
olr.fit = MASS::polr(as.formula(f_str), data=data)
print("模型拟合完成")
# coefficients
print("系数提取中...")
f = as.formula(f_str)
out.coef.raw = broom::tidy(olr.fit, conf.int = TRUE, conf.level = 0.95) |>
mutate(`P-value` = 2 * (1 - pnorm(abs(statistic)))) |>
rename(
Variable = term,
`Coefficient` = estimate,
`Standar Error` = std.error,
`Z-value` = statistic,
`Lower 95% CI` = conf.low,
`Upper 95% CI` = conf.high
)
print("系数提取完成")
# report
out.coef.report = out.coef.raw |>
mutate(
`Odds Ratio` = style_number(exp(`Coefficient`), digits = digits_coef),
`Coefficient (95% CI)` = paste(style_number(`Coefficient`, digits = digits_coef),
" (", style_number(`Lower 95% CI`, digits = digits_coef), ", ",
style_number(`Upper 95% CI`, digits = digits_coef), ")", sep=""),
`P-value` = style_pvalue(`P-value`, digits = digits_p)
) |>
dplyr::select(`Variable`, `Odds Ratio`, `Coefficient (95% CI)`, `P-value`)
print("报告表生成完成")
# Porportional Odds Assumption is necessary
assumption = brant(olr.fit)
print("假设检验完成")
# 输出结果
out_list = list(
"coef" = out.coef.raw,
"report" = out.coef.report,
"assumption" = assumption,
"model" = olr.fit
)
print("输出结果完成")
return(out_list)
}
summary = model_ordinal_regression(seer_multi, "SurvivalStatus", NA, f_x = "Sex + Race + Grade + Stage + PrimarySite + Chemotherapy")
