python - 使用 rpy2 将 R 代码转换为 Python 代码

标签 python r rpy2

我是 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/

相关文章:

python - fcntl.lockf() 以何种方式锁定文件?

python - 不要进入 for 循环中的下一次迭代

python - xarray : Combine data variables with discrete observations in a new continuous dimension

r - R中字母之间所有可能的点组合

r - 等效模型的不同 R 平方

python - 在 rpy2 中关闭 ggplot2 网格

python - 在 Python 中使用 Rpy2 对具有翻转坐标的 ggplot2 条形图进行排序

python - 具有多个参数的多处理在 Python 2.7 中运行

r - 如何在R中的xyplot中获得阴影背景?

python - 通过 RPy 查看 R 数据示例(示例 : lmeSplines)