关于R语言修正对数回归方程显示及生成方程汇总数据框的问询
解决方案
问题1:修正回归方程显示ln(x)
默认的stat_regline_equation会将log(x)拟合的模型变量显示为x,需要自定义标签格式并开启解析功能来显示ln(x)。修改你的ggplot代码中stat_regline_equation部分如下:
plots <- purrr::map(iris, function(y) { ggplot(rotated.plot.data, aes(x=instrument.supersaturation, y={{ y }})) + geom_point() + geom_smooth(method="lm", formula = y~log(x)) + stat_regline_equation( formula = y~log(x), # 自定义方程格式,显示ln(x) format_string = "y = {intercept} + {slope}*ln(x)\nR² = {r.squared}", parse = TRUE # 开启LaTeX解析,让ln(x)正确显示 ) + ylab("Nccn/Ncn") + xlab("instrument supersaturation(%)") })
如果需要更精确的小数位数,可以在format_string中指定,比如{intercept:.2f}来保留两位小数:
format_string = "y = {intercept:.2f} + {slope:.2f}*ln(x)\nR² = {r.squared:.2f}"
问题2:生成对数回归方程汇总数据框
直接使用lm()函数拟合模型并提取参数,结合purrr::map_dfr生成汇总数据框,比从ggplot的stat中提取更高效:
library(tidyverse) # 遍历所有目标列,拟合模型并汇总结果 reg_summary <- purrr::map_dfr(names(iris), function(col_name) { # 提取当前列的响应变量和自变量 model_data <- rotated.plot.data %>% select(x = instrument.supersaturation, y = all_of(col_name)) %>% drop_na() # 去除缺失值,避免拟合出错 # 拟合对数回归模型 lm_model <- lm(y ~ log(x), data = model_data) # 提取模型参数和统计量 coefs <- coef(lm_model) intercept <- coefs[["(Intercept)"]] slope <- coefs[["log(x)"]] r_squared <- summary(lm_model)$r.squared # 返回单条记录的 tibble tibble( column_name = col_name, intercept = round(intercept, 2), slope = round(slope, 2), r_squared = round(r_squared, 2), regression_equation = sprintf("y = %.2f + %.2f*ln(x)", intercept, slope) ) }) # 查看结果 print(reg_summary)
这个数据框会包含每一列的名称、回归截距、斜率、R²值,以及完整的回归方程字符串。
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

