3

I am new to R and actually, I knew nothing about R syntax. So, I found the rpy2 package(version 2.6.1) and trying to make use of the R regression fitting function for data analysis. However, I failed to extract the regression coefficients using rpy2. If anyone can help to tell how to pull out the regression equation coefficients, like R^2, P etc., Really thanks a lot.

I found out a R code to achieve this however, I cannot convert it to python code currently. The R code I have found is shown following:

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)))
}

1 Answer 1

3
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)))
    }""")

With this you can call the function ggplotRegression in your Python code.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Lgautier, thank you so much for your answer. In that way, I still need to write code using R syntax. Do you have any related materials for me to write the corresponding code in Python using rpy2 package? If not, could you please help tell me how to call this function in Python? So sorry that I cannot vote your answer because this is the first time I use stachoverflow and my reputation is too low to vote.
May be you did, but just in case: did you check the links in Section "Documentation" at rpy2.bitbucket.org ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.