R With PowerBI: A Step-by-Step Guide
There's been a lot of interest everywhere on how to integrate R scripts with Microsoft PowerBI dashboards. Here is a step by step guide to this.
Lets assume that you have some readymade R code available, for example, with the ggplot2 library. Lets use the following scripts to perform analytics using CHOL data.
Open R studio or R Package (CRAN) & install ggplot2 library first.
- Paste the following R script and execute it:
- Next, execute the following pieces of R code to find out the binwidth argument using the ‘qplot()‘ function:
- Lets get some help from the hist() function in R:
- Now, add an I() function for nested colors:
- Next, adjust ggplot2 a little by using the following code:
- Plot a bar graph with the following code:
- Next, open the PowerBI desktop tool. You can download it for free from this link. Now, click on the Get Data tab to start exploring and connect with an R dataset.
- Next, you can also choose the ‘custom R visual’ in PowerBI desktop visualizations and provide the required R scripts to build visuals and finally click ‘Run’.
- Build all the R function visuals by following the same steps and save the dashboard.
- You can refresh an R script in Power BI Desktop. When you refresh an R script, Power BI Desktop runs the R script again in the Power BI Desktop environment.
install.packages(‘ggplot2’)
library(ggplot2)
chol <- read.table(url(“http://assets.datacamp.com/blog_assets/chol.txt”"), header = TRUE)
#Take the column “AGE” from the “chol” dataset and make a histogram it
qplot(chol$AGE , geom = “histogram”)
ggplot(data-chol, aes(chol$AGE)) + geom_histogram()
You should be able to see the visual output like this.
qplot(chol$AGE,
geom = “histogram”,
binwidth = 0.5)
#Lets take help from hist() function
qplot(chol$AGE,
geom=”histogram”,
binwidth = 0.5,
main = “Histogram for Age”,
xlab = “Age”,
fill=I(“blue”))
#Add col argument, I() function where nested color.
qplot(chol$AGE,
geom=”histogram”,
binwidth = 0.5,
main = “Histogram for Age”,
xlab = “Age”,
fill=I(“blue”),
col=I(“red”))
#Adjusting ggplot
ggplot(data=chol, aes(chol$AGE)) +
geom_histogram(breaks=seq(20, 50, by = 2),
col=”red”,
fill=”green”,
alpha = .2) +
labs(title=”Histogram for Age”) +
labs(x=”Age”, y=”Count”) +
xlim(c(18,52)) +
ylim(c(0,30))
#Plotting Bar Graph
qplot(chol$AGE,
geom=”bar”,
binwidth = 0.5,
main = “Bar Graph for Mort”,
xlab = “Mort”,
fill=I(“Red”))
If you already have R installed on the same system as PowerBI, you just need to paste the R scripts in the code pen. Otherwise you need to install R in the system where you are using the PowerBI desktop like this:
Related Refcard:
R Essentials