SlideShare a Scribd company logo
R – Excel Integration using XLConnect package

         Example of writing R data frames and graphs to Excel templates


Create and save Excel template on Desktop:

          •   Two predefined cell styles called header (Font - Calibry (Body), Font Style - Bold
              Italic, Size - 11, Fill - Blue) and number (Number, Comma 1000 separator, Decimal
              Places - 3).
          •   Sheet2 – Table with formatting range Sheet2!B2:C3 as Number, Comma 1000
              Separator and Decimal Places - 2




          •   Named Region graph - Sheet2!$A$5



R code (requires libraries XLConnect, plyr and ggplot2):

#Import XLConnect library

library(XLConnect)

#Define working directory

setwd("C:UsersPCDesktop")

#Simulate some data frame

set.seed(10)

DF <- data.frame(Gender=sample(c("female", "male"), 100, rep=TRUE),

                    Consumption=runif(100, 1000, 2000), stringsAsFactors=FALSE)

#Load Excel template file named template.xls
wb <- loadWorkbook("C:UsersPCDesktoptemplate.xlsx")

#Import predefined cell styles

header <- getCellStyle(wb, name = "header")

number <- getCellStyle(wb, name="number")

#Write data frame to Sheet1

writeWorksheet(wb, DF, sheet="Sheet1", startRow=1, startCol=1)

#Applied predefined cell styles

setCellStyle(wb, sheet="Sheet1", row=rep(1,ncol(DF)), col=rep(c(1:2), 1),

            cellstyle=header)

setCellStyle(wb, sheet="Sheet1", row=2:(nrow(DF)+1), col=rep(c(1:2),
each=nrow(DF)),

            cellstyle=number)

#Keep predefined cell style from Sheet2

setStyleAction(wb, XLC$"STYLE_ACTION.PREDEFINED")

#Summarize data by gender using plyr package

library(plyr)

DF1 <- ddply(DF, .(Gender), summarise,

                              No_Respondents=length(Gender),

                              Total_Consumption=sum(Consumption))

#Write data frame to Sheet2

writeWorksheet(wb, sheet="Sheet2", DF1[,-1], header=FALSE, startRow=2,
startCol=2)

#Create graph using ggplot2 library and save it as png file

png("graph1.png")

library(ggplot2)

ggplot(DF1, aes(Gender, No_Respondents, fill=Gender)) +

geom_bar(position = "dodge")+ scale_fill_manual(values=c("darkgray",
"lightblue"))

dev.off()

#Add graph (png to) to Excel file

#Named region graph on Sheet2

addImage(wb, filename = "graph1.png", name = "graph",
originalSize = TRUE)

#Deleted png file from working directory

file.remove("graph1.png")

#Save changes

saveWorkbook(wb)

R info session:
> sessionInfo()

R version 2.15.0 (2012-03-30)

Platform: i386-pc-mingw32/i386 (32-bit)



locale:

[1] LC_COLLATE=English_United States.1252       LC_CTYPE=English_United States.1252

[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C

[5] LC_TIME=English_United States.1252



attached base packages:

[1] stats         graphics   grDevices utils     datasets   methods    base



other attached packages:

[1] ggplot2_0.9.1            plyr_1.7.1          XLConnect_0.1-9
XLConnectJars_0.1-4

[5] rJava_0.9-3



loaded via a namespace (and not attached):

 [1] colorspace_1.1-1        dichromat_1.2-4    digest_0.5.2          grid_2.15.0

 [5] labeling_0.1            MASS_7.3-17        memoise_0.1           munsell_0.3

 [9] proto_0.3-9.2           RColorBrewer_1.0-5 reshape2_1.2.1        scales_0.2.1

[13] stringr_0.6
Results:

Sheet1:




Sheet2:

More Related Content

PDF
PDF
Py lecture5 python plots
PDF
Linux/Rails学習用テキスト
DOCX
A Shiny Example-- R
PPTX
An introduction to matlab
PDF
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
PPTX
กลุ่ม6
PDF
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
Py lecture5 python plots
Linux/Rails学習用テキスト
A Shiny Example-- R
An introduction to matlab
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
กลุ่ม6
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...

What's hot (20)

PDF
Machine Learning Game Changer for IT - Maartens Lourens
PPTX
Lrz kurse: r visualisation
PDF
Logging in JavaScript - Part-5
DOCX
ggtimeseries-->ggplot2 extensions
PPTX
Create a correlation plot from joined tables and lag times
DOC
C# example (Polymorphesim)
PDF
Excel macro for integration of a function
PPTX
Python Set.pptx
PDF
SATySFiのこれからの課題たち
KEY
R meets Hadoop
PDF
Data Visualization With R: Learn To Modify Font Of Graphical Parameters
PPTX
A quick introduction to R
PDF
R Data Visualization: Learn To Add Text Annotations To Plots
PDF
Hive function-cheat-sheet
PPTX
Python programing
PPTX
random forest regression
PDF
Data Visualization With R: Learn To Modify Title, Axis Labels & Range
KEY
RHadoop の紹介
PPTX
Mapfilterreducepresentation
DOCX
CLASS XII COMPUTER SCIENCE MONTHLY TEST PAPER
Machine Learning Game Changer for IT - Maartens Lourens
Lrz kurse: r visualisation
Logging in JavaScript - Part-5
ggtimeseries-->ggplot2 extensions
Create a correlation plot from joined tables and lag times
C# example (Polymorphesim)
Excel macro for integration of a function
Python Set.pptx
SATySFiのこれからの課題たち
R meets Hadoop
Data Visualization With R: Learn To Modify Font Of Graphical Parameters
A quick introduction to R
R Data Visualization: Learn To Add Text Annotations To Plots
Hive function-cheat-sheet
Python programing
random forest regression
Data Visualization With R: Learn To Modify Title, Axis Labels & Range
RHadoop の紹介
Mapfilterreducepresentation
CLASS XII COMPUTER SCIENCE MONTHLY TEST PAPER
Ad

Viewers also liked (13)

PDF
Visualization of contingency table in R - vcd package
PDF
Debt Collection Report - using R in Finance
PDF
R and Access 2007
PDF
Data aggregation in R
PDF
Polar plots with R
PDF
Roll Rate Model - Using R in Finance
PDF
Intro to R for SAS and SPSS User Webinar
PDF
Seguimiento del modelo interno de riesgo
 
PPTX
Testing of hypothesis case study
PDF
Data Exploration, Validation and Sanitization
PDF
Model building in credit card and loan approval
PPTX
Decision tree
PPTX
Credit Risk Model Building Steps
Visualization of contingency table in R - vcd package
Debt Collection Report - using R in Finance
R and Access 2007
Data aggregation in R
Polar plots with R
Roll Rate Model - Using R in Finance
Intro to R for SAS and SPSS User Webinar
Seguimiento del modelo interno de riesgo
 
Testing of hypothesis case study
Data Exploration, Validation and Sanitization
Model building in credit card and loan approval
Decision tree
Credit Risk Model Building Steps
Ad

Similar to R-Excel Integration (20)

PPT
Easy R
PDF
Basic and logical implementation of r language
PDF
RDataMining slides-r-programming
PDF
R programming & Machine Learning
PDF
Introduction to r studio on aws 2020 05_06
PPTX
R Introduction
PPTX
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
PPT
r,rstats,r language,r packages
PDF
R - the language
PDF
Data Analysis with R (combined slides)
PPTX
statistical computation using R- an intro..
PPTX
R language introduction
PPTX
Data Exploration in R.pptx
PPT
Introduction to R for Data Science Technology
PPT
Advanced Data Analytics with R Programming.ppt
PDF
Rtips123
PPTX
Exploratory Analysis Part1 Coursera DataScience Specialisation
PPT
introduction to R with example, Data science
PPT
PDF
R basics
Easy R
Basic and logical implementation of r language
RDataMining slides-r-programming
R programming & Machine Learning
Introduction to r studio on aws 2020 05_06
R Introduction
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
r,rstats,r language,r packages
R - the language
Data Analysis with R (combined slides)
statistical computation using R- an intro..
R language introduction
Data Exploration in R.pptx
Introduction to R for Data Science Technology
Advanced Data Analytics with R Programming.ppt
Rtips123
Exploratory Analysis Part1 Coursera DataScience Specialisation
introduction to R with example, Data science
R basics

R-Excel Integration

  • 1. R – Excel Integration using XLConnect package Example of writing R data frames and graphs to Excel templates Create and save Excel template on Desktop: • Two predefined cell styles called header (Font - Calibry (Body), Font Style - Bold Italic, Size - 11, Fill - Blue) and number (Number, Comma 1000 separator, Decimal Places - 3). • Sheet2 – Table with formatting range Sheet2!B2:C3 as Number, Comma 1000 Separator and Decimal Places - 2 • Named Region graph - Sheet2!$A$5 R code (requires libraries XLConnect, plyr and ggplot2): #Import XLConnect library library(XLConnect) #Define working directory setwd("C:UsersPCDesktop") #Simulate some data frame set.seed(10) DF <- data.frame(Gender=sample(c("female", "male"), 100, rep=TRUE), Consumption=runif(100, 1000, 2000), stringsAsFactors=FALSE) #Load Excel template file named template.xls
  • 2. wb <- loadWorkbook("C:UsersPCDesktoptemplate.xlsx") #Import predefined cell styles header <- getCellStyle(wb, name = "header") number <- getCellStyle(wb, name="number") #Write data frame to Sheet1 writeWorksheet(wb, DF, sheet="Sheet1", startRow=1, startCol=1) #Applied predefined cell styles setCellStyle(wb, sheet="Sheet1", row=rep(1,ncol(DF)), col=rep(c(1:2), 1), cellstyle=header) setCellStyle(wb, sheet="Sheet1", row=2:(nrow(DF)+1), col=rep(c(1:2), each=nrow(DF)), cellstyle=number) #Keep predefined cell style from Sheet2 setStyleAction(wb, XLC$"STYLE_ACTION.PREDEFINED") #Summarize data by gender using plyr package library(plyr) DF1 <- ddply(DF, .(Gender), summarise, No_Respondents=length(Gender), Total_Consumption=sum(Consumption)) #Write data frame to Sheet2 writeWorksheet(wb, sheet="Sheet2", DF1[,-1], header=FALSE, startRow=2, startCol=2) #Create graph using ggplot2 library and save it as png file png("graph1.png") library(ggplot2) ggplot(DF1, aes(Gender, No_Respondents, fill=Gender)) + geom_bar(position = "dodge")+ scale_fill_manual(values=c("darkgray", "lightblue")) dev.off() #Add graph (png to) to Excel file #Named region graph on Sheet2 addImage(wb, filename = "graph1.png", name = "graph",
  • 3. originalSize = TRUE) #Deleted png file from working directory file.remove("graph1.png") #Save changes saveWorkbook(wb) R info session: > sessionInfo() R version 2.15.0 (2012-03-30) Platform: i386-pc-mingw32/i386 (32-bit) locale: [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 [3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C [5] LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] ggplot2_0.9.1 plyr_1.7.1 XLConnect_0.1-9 XLConnectJars_0.1-4 [5] rJava_0.9-3 loaded via a namespace (and not attached): [1] colorspace_1.1-1 dichromat_1.2-4 digest_0.5.2 grid_2.15.0 [5] labeling_0.1 MASS_7.3-17 memoise_0.1 munsell_0.3 [9] proto_0.3-9.2 RColorBrewer_1.0-5 reshape2_1.2.1 scales_0.2.1 [13] stringr_0.6