Save the result from "summary(lm)" to use in PowerBi

Viewed 296

Is it possible to save an summary(lm) object in a format usable in PowerBI?

Lets say the following:

data <- mpg
lm <- lm(hwy ~ displ, data = mpg)
summary(lm)

Output:

Call:
lm(formula = hwy ~ displ, data = mpg)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.1039 -2.1646 -0.2242  2.0589 15.0105 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  35.6977     0.7204   49.55   <2e-16 ***
displ        -3.5306     0.1945  -18.15   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.836 on 232 degrees of freedom
Multiple R-squared:  0.5868,    Adjusted R-squared:  0.585 
F-statistic: 329.5 on 1 and 232 DF,  p-value: < 2.2e-16

I would lake to save this information as gglpot2 object, or picture in general, that I can display in Power BI. So that we can use this as a template for a fast regressions inside Power BI. This since Power BI only can display R code that results in a "plot" and not text.

I have tried:

textplot(capture.output(summary(lm)))

But I first got this error:

>install.packages('textplot')
Warning in install.packages : 
    package ‘textplot’ is not available (for R version 3.5.3)

And unfortunately Power BI doesn't supports textplot().

EDIT: Clarification I'm not looking to plot a regression line nor plane. I'm looking for a way to save the text output from "summary(lm)" as a plot object that I can display in Power BI.

2 Answers

Try something like this:

fit <- lm(hwy ~ displ, data = mpg)
txt = capture.output(print(summary(fit)))

plot(NULL,xlim=c(-1,1),ylim=c(-1,1),xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
text(x=0,y=0,paste(txt,collapse="\n"))

enter image description here

You might need to look at using stringr::str_pad to make the text prettier.. but this should get you something that works.

This is how you put it on ggplot2:

ggplot() + xlim(c(-1,1)) + ylim(c(-1,1)) + 
geom_text(aes(x=0,y=0,label=paste(txt,collapse="\n"))) + 
    theme_void()

enter image description here

This example should be useful for you. To apply here:

plot(hwy ~ displ, data=mpg)
abline(lm1)

enter image description here

For the ggplot2 solution, this works:

ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method='lm', formula=y~x)

enter image description here

Related