SlideShare a Scribd company logo
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
The ultimate tools to produce rich
complex, template based, high-quality
tables and Word/Power Point documents with R
with application to the Clinical Research Study Reports
officer ● flextable ● rvg ● devEMF ● mschart
by David Gohel: https://github.com/davidgohel
flextable – the new standard of drawing tables
The flextable package allows you to create rich, complex tables in MS Word. You can control
almost everything: fonts (face, size, style - bold/italic/sub-/superscript/underline, colour), cell
background, cell margins, cell alignment, cell merge (works in headers, footers and table
body), conditional formatting and merging, frames around cells/tables (line stile, width,
colour), embedding pictures, Word special field.
When necessary, you can also modify the underlying XML document.
I could write a poem on how much it’s flexible and rich in functions, but let’s the pictures
speak! Below you will find some real examples of the “table shells” I made with flextable.
Examples
It looks a bit rudimentary, but that’s just a to show what can be done with it.
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
How about big tables?
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
How complex tables can be handled? Any!
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
Longitudinal analysis? No problem at all!
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
Clinical programmers should find it familiar ☺
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
officer – R meets Word and Power Point
officer is the workhorse of the suite. Briefly – it can generate complete Word and Power Point
documents, paragraph by paragraph, page by page. With officer you can search and replace
the content using regular expressions or bookmarks. You can adjust paragraph and font styles,
change fonts and colors. You can insert sections and page breaks. Operate in headers and
footers. Embed pictures from file bitmaps and metafiles or generated ggplot2 graphs.
But that’s not all! The officer package allows one to use templates with pre-defined styles.
Now you should have the “a-ha!” moment.
Templates – what a powerful mechanism!
Templates allow you to create complex reports with pre-defined structure, which also re-used
pre-defined styles (e.g. corporate layout, colors).
Look at the picture below. There are placeholders for the content (tables, listings, figures)
marked in yellow. I added some content, but it doesn’t matter now. You will add your own. R
can access them via officer: it parses the document, finds all those paragraphs (e.g. by style)
so you can interpret their content.
You could employ some naming convention (or some Excel file with mapping, maybe a even a
database – it’s up to you) to determine which R file should be called, run it and embed the
output right here.
This way you can define analysis scenario (at least its automated part) in the Word report
directly, and pre-populate it with initial stuff (the first page content, TOC (for chapters, tables,
figures), initial chapters) interleaved with the "scenario" of the analysis.
Then, you can programmatically replace the placeholders (everywhere: in the document body,
page headers, footers, and even in... tables) with actual values, which produces the final
Sounds good!
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
Want more fun?
With officer you can also transfer the R output directly to Word.
Here – the output of the console.
You can also export the flextable object temporarily to Word just with a single line:
print( flextable(your_data_frame), "docx")
which opens a Word window with a temporary document storing your table. You can format
it here and copy/paste elsewhere, if you don't want to spend your time on writing the code
doing that in a more sophisticated manner.
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
This way you can transfer your model coefficients directly to R (with broom package), which
minimizes the risk of making typos and saving your time.
Look below for some examples:
devEMF – no more raster graphics!
You know this pain – you copy/paste a graph into Word as a bitmap. Then you want to scale
(resize) it. And what do you get? Well, it may look OK on your screen, but when you print it, it
often looks just ugly and blurred.
With devEMF you can transform ggplot2 charts directly into metafiles and embed them in
Word. Being a vector graphics, they are resizable without losing the quality.
Look below. I resized the plot enormously. See? No blur at all! It’s a vector drawing.
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
But hold on, there’s more fun with the “rvg”!
rvg – ggplot2 meets PowerPoint!
With the rvg package you can convert ggplot2 graphs into PPTx presentations, where the
graph will be also editable. Yes! You read correctly! The vector graphics is converted to a set
of MS Office drawings:: lines, arcs, labels, circles, rectangles - so you can modify any part of
the chart.
Let’s imagine you have a presentation in just 10 minutes. Suddenly you realize you made a
typo on the main chart. It looks rather unprofessional, doesn’t it? You have no time to re-
create the plot, but that’s not a problem! You exported your graphs to PPTx, so you can edit
them in Power Point! Fix the typo and have a good presentation!
Look below. Isn’t that awesome?
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
mschart – R meets Excel charts allows you to insert basic Excel charts (editable in
the Office way, not just a drawing). I don’t use this option yet, but maybe you find it useful.
https://github.com/ardata-fr/mschart
With officer you can also fill up CONSORT diagrams made in Word (Word drawings) by
replacing the placeholders in the shapes. Yes, it’s so simple – I added a bookmark to each text
I wanted to replace. For example, in “Active treatment n= XX I bookmarked the “XX”.
Then I replaced it with the code, by iterating through the bookmarks found by the officer. This
way I was able to transform the template into the final diagram with actual numbers.
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
What about the HTML?
Lots of R packages can deal with complex tables in HTML and office is not an exception here. Even, if
the flextable + officer is mainly about the Office documents, it’s capable of producing HTML as well.
Useful links:
• https://davidgohel.github.io/officer/
• https://davidgohel.github.io/flextable/
• https://davidgohel.github.io/rvg/
• https://ardata-fr.github.io/mschart/
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
Want to experiment a bit?
Transfer model summary directly to Word
> (model <- lm(mpg~ as.factor(cyl) + as.factor(gear), data=mtcars))
Call:
lm(formula = mpg ~ as.factor(cyl) + as.factor(gear), data = mtcars)
Coefficients:
(Intercept) as.factor(cyl)6 as.factor(cyl)8 as.factor(gear)4 as.factor(gear)5
25.428 -6.656 -10.542 1.324 1.500
> print( flextable::flextable( broom::tidy( model)), "docx")
> print( flextable::flextable( broom::tidy( aov(model))), "docx")
term df sumsq meansq statistic p.value
as.factor(cyl) 2.000 824.785 412.392 38.001 0.000
as.factor(gear) 2.000 8.252 4.126 0.380 0.687
Residuals 27.000 293.011 10.852
Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
Export R drawings to a vector graphics you can resize without blur
ggplot2_to_Word <- function(plot, where){
filename <- tempfile(fileext = ".emf")
devEMF::emf(file = filename, width = 6, height = 7)
print(plot)
dev.off()
officer::read_docx() %>%
officer::body_add_img(src = filename, width = 6, height = 7) %>%
print(target = where)
}
ggplot2_to_Word( ggplot2::qplot(mtcars$mpg), "test.docx")
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
[1] "C:/tmp/test.docx"
Export ggplot2 to an editable MS Office® drawing (in PowerPoint®)
ggplot2_to_pptx <- function(plots, where){
doc <- officer::read_pptx()
for(plot in plots){
if(ggplot2::is.ggplot(plot)) {
doc <- officer::add_slide(doc,
layout = "Title and Content",
master = "Office Theme") %>%
officer::ph_with(rvg::dml(ggobj = plot),
location = officer::ph_location_type(type = "body"))
}
}
print(doc, target = where)
}
ggplot2_to_pptx( list(ggplot2::qplot(mtcars$mpg)), "test.pptx")
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
[1] "C:/tmp/test.pptx"
0
1
2
3
4
5
10 15 20 25 30 35
mtcars$mpg

More Related Content

What's hot

What is Discrete Mathematics?
What is Discrete Mathematics?What is Discrete Mathematics?
What is Discrete Mathematics?
Brainware University
 
Higher order differential equations
Higher order differential equationsHigher order differential equations
Higher order differential equations
Mateus Nieves Enrique - DIE-UD
 
Recursion DM
Recursion DMRecursion DM
Recursion DM
Rokonuzzaman Rony
 
1st order differential equations
1st order differential equations1st order differential equations
1st order differential equations
Nisarg Amin
 
Support Vector Machine Tutorial 한국어
Support Vector Machine Tutorial 한국어Support Vector Machine Tutorial 한국어
Support Vector Machine Tutorial 한국어
Jungkyu Lee
 
선형대수 01. 선형성의 정의와 1차 연립방정식의 의미
선형대수 01. 선형성의 정의와 1차 연립방정식의 의미선형대수 01. 선형성의 정의와 1차 연립방정식의 의미
선형대수 01. 선형성의 정의와 1차 연립방정식의 의미
AHRA CHO
 
4.3 data structures records
4.3 data structures   records4.3 data structures   records
4.3 data structures records
missstevenson01
 
Convolution as matrix multiplication
Convolution as matrix multiplicationConvolution as matrix multiplication
Convolution as matrix multiplication
Edwin Efraín Jiménez Lepe
 
Branch & bound
Branch & boundBranch & bound
Branch & bound
kannanchirayath
 
Implementing Minimum Error Rate Classifier
Implementing Minimum Error Rate ClassifierImplementing Minimum Error Rate Classifier
Implementing Minimum Error Rate Classifier
Dipesh Shome
 
Newton's Forward/Backward Difference Interpolation
Newton's Forward/Backward  Difference InterpolationNewton's Forward/Backward  Difference Interpolation
Newton's Forward/Backward Difference Interpolation
VARUN KUMAR
 
Maths partial differential equation Poster
Maths partial differential equation PosterMaths partial differential equation Poster
Maths partial differential equation Poster
Er. Ashish Pandey
 
5.1 greedy
5.1 greedy5.1 greedy
5.1 greedy
Krish_ver2
 
Methods of solving ODE
Methods of solving ODEMethods of solving ODE
Methods of solving ODE
kishor pokar
 
Levenberg - Marquardt (LM) algorithm_ aghazade
Levenberg - Marquardt (LM) algorithm_ aghazadeLevenberg - Marquardt (LM) algorithm_ aghazade
Levenberg - Marquardt (LM) algorithm_ aghazade
Inistute of Geophysics, Tehran university , Tehran/ iran
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Gaussian Integration
Gaussian IntegrationGaussian Integration
Gaussian Integration
Reza Rahimi
 
Proofs and disproofs
Proofs and disproofsProofs and disproofs
Proofs and disproofs
Lakshmi R
 
cyclic_code.pdf
cyclic_code.pdfcyclic_code.pdf
cyclic_code.pdf
rahelbirhanu1
 
プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列
プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列
プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列
Taketo Sano
 

What's hot (20)

What is Discrete Mathematics?
What is Discrete Mathematics?What is Discrete Mathematics?
What is Discrete Mathematics?
 
Higher order differential equations
Higher order differential equationsHigher order differential equations
Higher order differential equations
 
Recursion DM
Recursion DMRecursion DM
Recursion DM
 
1st order differential equations
1st order differential equations1st order differential equations
1st order differential equations
 
Support Vector Machine Tutorial 한국어
Support Vector Machine Tutorial 한국어Support Vector Machine Tutorial 한국어
Support Vector Machine Tutorial 한국어
 
선형대수 01. 선형성의 정의와 1차 연립방정식의 의미
선형대수 01. 선형성의 정의와 1차 연립방정식의 의미선형대수 01. 선형성의 정의와 1차 연립방정식의 의미
선형대수 01. 선형성의 정의와 1차 연립방정식의 의미
 
4.3 data structures records
4.3 data structures   records4.3 data structures   records
4.3 data structures records
 
Convolution as matrix multiplication
Convolution as matrix multiplicationConvolution as matrix multiplication
Convolution as matrix multiplication
 
Branch & bound
Branch & boundBranch & bound
Branch & bound
 
Implementing Minimum Error Rate Classifier
Implementing Minimum Error Rate ClassifierImplementing Minimum Error Rate Classifier
Implementing Minimum Error Rate Classifier
 
Newton's Forward/Backward Difference Interpolation
Newton's Forward/Backward  Difference InterpolationNewton's Forward/Backward  Difference Interpolation
Newton's Forward/Backward Difference Interpolation
 
Maths partial differential equation Poster
Maths partial differential equation PosterMaths partial differential equation Poster
Maths partial differential equation Poster
 
5.1 greedy
5.1 greedy5.1 greedy
5.1 greedy
 
Methods of solving ODE
Methods of solving ODEMethods of solving ODE
Methods of solving ODE
 
Levenberg - Marquardt (LM) algorithm_ aghazade
Levenberg - Marquardt (LM) algorithm_ aghazadeLevenberg - Marquardt (LM) algorithm_ aghazade
Levenberg - Marquardt (LM) algorithm_ aghazade
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
 
Gaussian Integration
Gaussian IntegrationGaussian Integration
Gaussian Integration
 
Proofs and disproofs
Proofs and disproofsProofs and disproofs
Proofs and disproofs
 
cyclic_code.pdf
cyclic_code.pdfcyclic_code.pdf
cyclic_code.pdf
 
プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列
プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列
プログラマのための線形代数再入門2 〜 要件定義から学ぶ行列式と逆行列
 

Similar to Flextable and Officer

R markdown and Rmdformats
R markdown and RmdformatsR markdown and Rmdformats
R markdown and Rmdformats
Hoffman Lab
 
RPE - Template formating, style and stylesheet usage
RPE - Template formating, style and stylesheet usageRPE - Template formating, style and stylesheet usage
RPE - Template formating, style and stylesheet usage
GEBS Reporting
 
Quick start learn dax basics in 30 minutes
Quick start   learn dax basics in 30 minutesQuick start   learn dax basics in 30 minutes
Quick start learn dax basics in 30 minutes
Компания Робот Икс
 
SQL Server - Introduction to TSQL
SQL Server - Introduction to TSQLSQL Server - Introduction to TSQL
SQL Server - Introduction to TSQL
Peter Gfader
 
CSS Less framework overview, Pros and Cons
CSS Less framework overview, Pros and ConsCSS Less framework overview, Pros and Cons
CSS Less framework overview, Pros and Cons
Sanjoy Kr. Paul
 
FME World Tour 2015: (EN) FME 2015 in action
FME World Tour 2015: (EN) FME 2015 in actionFME World Tour 2015: (EN) FME 2015 in action
FME World Tour 2015: (EN) FME 2015 in action
GIM_nv
 
Software Freedom Day Cleveland Presentation
Software Freedom Day Cleveland PresentationSoftware Freedom Day Cleveland Presentation
Software Freedom Day Cleveland Presentation
Bob McDonald
 
MS PowerPoint, Excel & Publisher Module
MS PowerPoint, Excel & Publisher ModuleMS PowerPoint, Excel & Publisher Module
MS PowerPoint, Excel & Publisher Module
Maria Dinah Alejo Dimacali
 
Applicationswpackage
ApplicationswpackageApplicationswpackage
Applicationswpackage
Bhalchandra Inamdar
 
Excel assignment help
Excel assignment helpExcel assignment help
Excel assignment help
Tutor Help Desk
 
Automating SolidWorks with Excel
Automating SolidWorks with ExcelAutomating SolidWorks with Excel
Automating SolidWorks with Excel
Razorleaf Corporation
 
WEB DEVELOPMENT
WEB DEVELOPMENTWEB DEVELOPMENT
WEB DEVELOPMENT
Gourav Kaushik
 
Data Science - Part II - Working with R & R studio
Data Science - Part II -  Working with R & R studioData Science - Part II -  Working with R & R studio
Data Science - Part II - Working with R & R studio
Derek Kane
 
Words in Code
Words in CodeWords in Code
Words in Code
Pete Goodliffe
 
Overview of Microsoft Office 2021.pdf
Overview of Microsoft Office 2021.pdfOverview of Microsoft Office 2021.pdf
Overview of Microsoft Office 2021.pdf
SoftwareDeals
 
Packages Computer Application in Business
Packages Computer Application in BusinessPackages Computer Application in Business
Packages Computer Application in Business
Nethan P
 
Apex RnD APEX 5 - Printing
Apex RnD APEX 5 - PrintingApex RnD APEX 5 - Printing
Apex RnD APEX 5 - Printing
Lino Schildenfeld
 
HTML literals, the JSX of the platform
HTML literals, the JSX of the platformHTML literals, the JSX of the platform
HTML literals, the JSX of the platform
Kenneth Rohde Christiansen
 
Software for paper formatting
Software for paper formatting Software for paper formatting
Software for paper formatting
salonibansal21
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
Robert Pickering
 

Similar to Flextable and Officer (20)

R markdown and Rmdformats
R markdown and RmdformatsR markdown and Rmdformats
R markdown and Rmdformats
 
RPE - Template formating, style and stylesheet usage
RPE - Template formating, style and stylesheet usageRPE - Template formating, style and stylesheet usage
RPE - Template formating, style and stylesheet usage
 
Quick start learn dax basics in 30 minutes
Quick start   learn dax basics in 30 minutesQuick start   learn dax basics in 30 minutes
Quick start learn dax basics in 30 minutes
 
SQL Server - Introduction to TSQL
SQL Server - Introduction to TSQLSQL Server - Introduction to TSQL
SQL Server - Introduction to TSQL
 
CSS Less framework overview, Pros and Cons
CSS Less framework overview, Pros and ConsCSS Less framework overview, Pros and Cons
CSS Less framework overview, Pros and Cons
 
FME World Tour 2015: (EN) FME 2015 in action
FME World Tour 2015: (EN) FME 2015 in actionFME World Tour 2015: (EN) FME 2015 in action
FME World Tour 2015: (EN) FME 2015 in action
 
Software Freedom Day Cleveland Presentation
Software Freedom Day Cleveland PresentationSoftware Freedom Day Cleveland Presentation
Software Freedom Day Cleveland Presentation
 
MS PowerPoint, Excel & Publisher Module
MS PowerPoint, Excel & Publisher ModuleMS PowerPoint, Excel & Publisher Module
MS PowerPoint, Excel & Publisher Module
 
Applicationswpackage
ApplicationswpackageApplicationswpackage
Applicationswpackage
 
Excel assignment help
Excel assignment helpExcel assignment help
Excel assignment help
 
Automating SolidWorks with Excel
Automating SolidWorks with ExcelAutomating SolidWorks with Excel
Automating SolidWorks with Excel
 
WEB DEVELOPMENT
WEB DEVELOPMENTWEB DEVELOPMENT
WEB DEVELOPMENT
 
Data Science - Part II - Working with R & R studio
Data Science - Part II -  Working with R & R studioData Science - Part II -  Working with R & R studio
Data Science - Part II - Working with R & R studio
 
Words in Code
Words in CodeWords in Code
Words in Code
 
Overview of Microsoft Office 2021.pdf
Overview of Microsoft Office 2021.pdfOverview of Microsoft Office 2021.pdf
Overview of Microsoft Office 2021.pdf
 
Packages Computer Application in Business
Packages Computer Application in BusinessPackages Computer Application in Business
Packages Computer Application in Business
 
Apex RnD APEX 5 - Printing
Apex RnD APEX 5 - PrintingApex RnD APEX 5 - Printing
Apex RnD APEX 5 - Printing
 
HTML literals, the JSX of the platform
HTML literals, the JSX of the platformHTML literals, the JSX of the platform
HTML literals, the JSX of the platform
 
Software for paper formatting
Software for paper formatting Software for paper formatting
Software for paper formatting
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
 

More from Adrian Olszewski

Logistic regression vs. logistic classifier. History of the confusion and the...
Logistic regression vs. logistic classifier. History of the confusion and the...Logistic regression vs. logistic classifier. History of the confusion and the...
Logistic regression vs. logistic classifier. History of the confusion and the...
Adrian Olszewski
 
Logistic regression - one of the key regression tools in experimental research
Logistic regression - one of the key regression tools in experimental researchLogistic regression - one of the key regression tools in experimental research
Logistic regression - one of the key regression tools in experimental research
Adrian Olszewski
 
Meet a 100% R-based CRO - The summary of a 5-year journey
Meet a 100% R-based CRO - The summary of a 5-year journeyMeet a 100% R-based CRO - The summary of a 5-year journey
Meet a 100% R-based CRO - The summary of a 5-year journey
Adrian Olszewski
 
Meet a 100% R-based CRO. The summary of a 5-year journey
Meet a 100% R-based CRO. The summary of a 5-year journeyMeet a 100% R-based CRO. The summary of a 5-year journey
Meet a 100% R-based CRO. The summary of a 5-year journey
Adrian Olszewski
 
Why are data transformations a bad choice in statistics
Why are data transformations a bad choice in statisticsWhy are data transformations a bad choice in statistics
Why are data transformations a bad choice in statistics
Adrian Olszewski
 
Modern statistical techniques
Modern statistical techniquesModern statistical techniques
Modern statistical techniques
Adrian Olszewski
 
Dealing with outliers in Clinical Research
Dealing with outliers in Clinical ResearchDealing with outliers in Clinical Research
Dealing with outliers in Clinical Research
Adrian Olszewski
 
The use of R statistical package in controlled infrastructure. The case of Cl...
The use of R statistical package in controlled infrastructure. The case of Cl...The use of R statistical package in controlled infrastructure. The case of Cl...
The use of R statistical package in controlled infrastructure. The case of Cl...
Adrian Olszewski
 
Rcommander - a menu-driven GUI for R
Rcommander - a menu-driven GUI for RRcommander - a menu-driven GUI for R
Rcommander - a menu-driven GUI for R
Adrian Olszewski
 
GNU R in Clinical Research and Evidence-Based Medicine
GNU R in Clinical Research and Evidence-Based MedicineGNU R in Clinical Research and Evidence-Based Medicine
GNU R in Clinical Research and Evidence-Based Medicine
Adrian Olszewski
 

More from Adrian Olszewski (10)

Logistic regression vs. logistic classifier. History of the confusion and the...
Logistic regression vs. logistic classifier. History of the confusion and the...Logistic regression vs. logistic classifier. History of the confusion and the...
Logistic regression vs. logistic classifier. History of the confusion and the...
 
Logistic regression - one of the key regression tools in experimental research
Logistic regression - one of the key regression tools in experimental researchLogistic regression - one of the key regression tools in experimental research
Logistic regression - one of the key regression tools in experimental research
 
Meet a 100% R-based CRO - The summary of a 5-year journey
Meet a 100% R-based CRO - The summary of a 5-year journeyMeet a 100% R-based CRO - The summary of a 5-year journey
Meet a 100% R-based CRO - The summary of a 5-year journey
 
Meet a 100% R-based CRO. The summary of a 5-year journey
Meet a 100% R-based CRO. The summary of a 5-year journeyMeet a 100% R-based CRO. The summary of a 5-year journey
Meet a 100% R-based CRO. The summary of a 5-year journey
 
Why are data transformations a bad choice in statistics
Why are data transformations a bad choice in statisticsWhy are data transformations a bad choice in statistics
Why are data transformations a bad choice in statistics
 
Modern statistical techniques
Modern statistical techniquesModern statistical techniques
Modern statistical techniques
 
Dealing with outliers in Clinical Research
Dealing with outliers in Clinical ResearchDealing with outliers in Clinical Research
Dealing with outliers in Clinical Research
 
The use of R statistical package in controlled infrastructure. The case of Cl...
The use of R statistical package in controlled infrastructure. The case of Cl...The use of R statistical package in controlled infrastructure. The case of Cl...
The use of R statistical package in controlled infrastructure. The case of Cl...
 
Rcommander - a menu-driven GUI for R
Rcommander - a menu-driven GUI for RRcommander - a menu-driven GUI for R
Rcommander - a menu-driven GUI for R
 
GNU R in Clinical Research and Evidence-Based Medicine
GNU R in Clinical Research and Evidence-Based MedicineGNU R in Clinical Research and Evidence-Based Medicine
GNU R in Clinical Research and Evidence-Based Medicine
 

Recently uploaded

一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 

Recently uploaded (20)

一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 

Flextable and Officer

  • 1. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ The ultimate tools to produce rich complex, template based, high-quality tables and Word/Power Point documents with R with application to the Clinical Research Study Reports officer ● flextable ● rvg ● devEMF ● mschart by David Gohel: https://github.com/davidgohel flextable – the new standard of drawing tables The flextable package allows you to create rich, complex tables in MS Word. You can control almost everything: fonts (face, size, style - bold/italic/sub-/superscript/underline, colour), cell background, cell margins, cell alignment, cell merge (works in headers, footers and table body), conditional formatting and merging, frames around cells/tables (line stile, width, colour), embedding pictures, Word special field. When necessary, you can also modify the underlying XML document. I could write a poem on how much it’s flexible and rich in functions, but let’s the pictures speak! Below you will find some real examples of the “table shells” I made with flextable. Examples It looks a bit rudimentary, but that’s just a to show what can be done with it.
  • 2. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ How about big tables?
  • 3. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ How complex tables can be handled? Any!
  • 4. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ Longitudinal analysis? No problem at all!
  • 5. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ Clinical programmers should find it familiar ☺
  • 6. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ officer – R meets Word and Power Point officer is the workhorse of the suite. Briefly – it can generate complete Word and Power Point documents, paragraph by paragraph, page by page. With officer you can search and replace the content using regular expressions or bookmarks. You can adjust paragraph and font styles, change fonts and colors. You can insert sections and page breaks. Operate in headers and footers. Embed pictures from file bitmaps and metafiles or generated ggplot2 graphs. But that’s not all! The officer package allows one to use templates with pre-defined styles. Now you should have the “a-ha!” moment. Templates – what a powerful mechanism! Templates allow you to create complex reports with pre-defined structure, which also re-used pre-defined styles (e.g. corporate layout, colors). Look at the picture below. There are placeholders for the content (tables, listings, figures) marked in yellow. I added some content, but it doesn’t matter now. You will add your own. R can access them via officer: it parses the document, finds all those paragraphs (e.g. by style) so you can interpret their content. You could employ some naming convention (or some Excel file with mapping, maybe a even a database – it’s up to you) to determine which R file should be called, run it and embed the output right here. This way you can define analysis scenario (at least its automated part) in the Word report directly, and pre-populate it with initial stuff (the first page content, TOC (for chapters, tables, figures), initial chapters) interleaved with the "scenario" of the analysis. Then, you can programmatically replace the placeholders (everywhere: in the document body, page headers, footers, and even in... tables) with actual values, which produces the final Sounds good!
  • 7. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/
  • 8. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ Want more fun? With officer you can also transfer the R output directly to Word. Here – the output of the console. You can also export the flextable object temporarily to Word just with a single line: print( flextable(your_data_frame), "docx") which opens a Word window with a temporary document storing your table. You can format it here and copy/paste elsewhere, if you don't want to spend your time on writing the code doing that in a more sophisticated manner.
  • 9. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ This way you can transfer your model coefficients directly to R (with broom package), which minimizes the risk of making typos and saving your time. Look below for some examples: devEMF – no more raster graphics! You know this pain – you copy/paste a graph into Word as a bitmap. Then you want to scale (resize) it. And what do you get? Well, it may look OK on your screen, but when you print it, it often looks just ugly and blurred. With devEMF you can transform ggplot2 charts directly into metafiles and embed them in Word. Being a vector graphics, they are resizable without losing the quality. Look below. I resized the plot enormously. See? No blur at all! It’s a vector drawing.
  • 10. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ But hold on, there’s more fun with the “rvg”! rvg – ggplot2 meets PowerPoint! With the rvg package you can convert ggplot2 graphs into PPTx presentations, where the graph will be also editable. Yes! You read correctly! The vector graphics is converted to a set of MS Office drawings:: lines, arcs, labels, circles, rectangles - so you can modify any part of the chart. Let’s imagine you have a presentation in just 10 minutes. Suddenly you realize you made a typo on the main chart. It looks rather unprofessional, doesn’t it? You have no time to re- create the plot, but that’s not a problem! You exported your graphs to PPTx, so you can edit them in Power Point! Fix the typo and have a good presentation! Look below. Isn’t that awesome?
  • 11. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ mschart – R meets Excel charts allows you to insert basic Excel charts (editable in the Office way, not just a drawing). I don’t use this option yet, but maybe you find it useful. https://github.com/ardata-fr/mschart With officer you can also fill up CONSORT diagrams made in Word (Word drawings) by replacing the placeholders in the shapes. Yes, it’s so simple – I added a bookmark to each text I wanted to replace. For example, in “Active treatment n= XX I bookmarked the “XX”. Then I replaced it with the code, by iterating through the bookmarks found by the officer. This way I was able to transform the template into the final diagram with actual numbers.
  • 12. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ What about the HTML? Lots of R packages can deal with complex tables in HTML and office is not an exception here. Even, if the flextable + officer is mainly about the Office documents, it’s capable of producing HTML as well. Useful links: • https://davidgohel.github.io/officer/ • https://davidgohel.github.io/flextable/ • https://davidgohel.github.io/rvg/ • https://ardata-fr.github.io/mschart/
  • 13. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ Want to experiment a bit? Transfer model summary directly to Word > (model <- lm(mpg~ as.factor(cyl) + as.factor(gear), data=mtcars)) Call: lm(formula = mpg ~ as.factor(cyl) + as.factor(gear), data = mtcars) Coefficients: (Intercept) as.factor(cyl)6 as.factor(cyl)8 as.factor(gear)4 as.factor(gear)5 25.428 -6.656 -10.542 1.324 1.500 > print( flextable::flextable( broom::tidy( model)), "docx") > print( flextable::flextable( broom::tidy( aov(model))), "docx") term df sumsq meansq statistic p.value as.factor(cyl) 2.000 824.785 412.392 38.001 0.000 as.factor(gear) 2.000 8.252 4.126 0.380 0.687 Residuals 27.000 293.011 10.852
  • 14. Compiled by Adrian Olszewski: https://www.linkedin.com/in/adrianolszewski/ Export R drawings to a vector graphics you can resize without blur ggplot2_to_Word <- function(plot, where){ filename <- tempfile(fileext = ".emf") devEMF::emf(file = filename, width = 6, height = 7) print(plot) dev.off() officer::read_docx() %>% officer::body_add_img(src = filename, width = 6, height = 7) %>% print(target = where) } ggplot2_to_Word( ggplot2::qplot(mtcars$mpg), "test.docx") `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. [1] "C:/tmp/test.docx" Export ggplot2 to an editable MS Office® drawing (in PowerPoint®) ggplot2_to_pptx <- function(plots, where){ doc <- officer::read_pptx() for(plot in plots){ if(ggplot2::is.ggplot(plot)) { doc <- officer::add_slide(doc, layout = "Title and Content", master = "Office Theme") %>% officer::ph_with(rvg::dml(ggobj = plot), location = officer::ph_location_type(type = "body")) } } print(doc, target = where) } ggplot2_to_pptx( list(ggplot2::qplot(mtcars$mpg)), "test.pptx") `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. [1] "C:/tmp/test.pptx" 0 1 2 3 4 5 10 15 20 25 30 35 mtcars$mpg