我是 R 的新手,实际上,我对 R 语法一无所知。因此,我找到了 rpy2 包(版本 2.6.1)并尝试利用 R 回归拟合函数进行数据分析。但是,我未能使用 rpy2 提取回归系数。谁能帮忙说一下回归方程的系数,比如R^2,P等,万分感谢。
我找到了一个 R 代码来实现这个,但是我目前无法将它转换为 python 代码。我找到的 R 代码如下所示:
ggplotRegression <- function (fit) {
require(ggplot2)
ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) +
geom_point() +
stat_smooth(method = "lm", col = "red") +
labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
"Intercept =",signif(fit$coef[[1]],5 ),
" Slope =",signif(fit$coef[[2]], 5),
" P =",signif(summary(fit)$coef[2,4], 5)))
}
最佳答案
from rpy2.robjects import r
ggplotRegression = r("""
function (fit) {
require(ggplot2)
ggplot(fit$model,
aes_string(x = names(fit$model)[2],
y = names(fit$model)[1])) +
geom_point() +
stat_smooth(method = "lm", col = "red") +
labs(title = paste("Adj R2 = ",
signif(summary(fit)$adj.r.squared, 5),
"Intercept =",
signif(fit$coef[[1]],5 ),
" Slope =",signif(fit$coef[[2]], 5),
" P =",signif(summary(fit)$coef[2,4],
5)))
}""")
有了它,您可以在 Python 代码中调用函数 ggplotRegression。
关于python - 使用 rpy2 将 R 代码转换为 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31983945/