<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/finalfit-knitr-and-r-markdown-for-quick-results/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.datasurg.net/2018/05/22/finalfit-knitr-and-r-markdown-for-quick-results/"> R – DataSurg</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Thank you for the many requests to provide some extra info on how best to get <code>finalfit</code> results out of RStudio, and particularly into Microsoft Word.</p>
<p>Here is how.</p>
<p>Make sure you are on the most up-to-date version of <code>finalfit</code>.</p>
<pre>devtools::install_github(&quot;ewenharrison/finalfit&quot;)</pre>
<p>What follows is for demonstration purposes and is not meant to illustrate model building. </p>
<p>Does a tumour characteristic (differentiation) predict 5-year survival?</p>
<h2>Demographics table</h2>
<p>First explore variable of interest (exposure) by making it the dependent.</p>

<pre>library(finalfit)
library(dplyr)

dependent = &quot;differ.factor&quot;

# Specify explanatory variables of interest
explanatory = c(&quot;age&quot;, &quot;sex.factor&quot;, 
  &quot;extent.factor&quot;, &quot;obstruct.factor&quot;, 
  &quot;nodes&quot;)</pre>

<p>Note this useful alternative way of specifying explanatory variable lists:</p>
<pre>colon_s %>% 
  select(age, sex.factor, 
  extent.factor, obstruct.factor, nodes) %>% 
  names() -> explanatory</pre>

<p>Look at associations between our exposure and other explanatory variables. Include missing data.</p>
<pre>colon_s %>% 
  summary_factorlist(dependent, explanatory, 
  p=TRUE, na_include=TRUE)</pre>

<pre>label              levels        Well    Moderate       Poor      p
       Age (years)           Mean (SD) 60.2 (12.8) 59.9 (11.7)  59 (12.8)  0.788
               Sex              Female   51 (11.6)  314 (71.7)  73 (16.7)  0.400
                                  Male    42 (9.0)  349 (74.6)  77 (16.5)       
  Extent of spread           Submucosa    5 (25.0)   12 (60.0)   3 (15.0)  0.081
                                Muscle   12 (11.8)   78 (76.5)  12 (11.8)       
                                Serosa   76 (10.2)  542 (72.8) 127 (17.0)       
                   Adjacent structures     0 (0.0)   31 (79.5)   8 (20.5)       
       Obstruction                  No    69 (9.7)  531 (74.4) 114 (16.0)  0.110
                                   Yes   19 (11.0)  122 (70.9)  31 (18.0)       
                               Missing    5 (25.0)   10 (50.0)   5 (25.0)       
             nodes           Mean (SD)   2.7 (2.2)   3.6 (3.4)  4.7 (4.4) &lt;0.001
Warning messages:
1: In chisq.test(tab, correct = FALSE) :
  Chi-squared approximation may be incorrect
2: In chisq.test(tab, correct = FALSE) :
  Chi-squared approximation may be incorrect</pre>
<p>Note missing data in <code>obstruct.factor</code>. We will drop this variable for now (again, this is for demonstration only). Also that <code>nodes</code> has not been labelled.<br>
There are small numbers in some variables generating chisq.test warnings (predicted less than 5 in any cell). Generate final table.</p>
<pre>Hmisc::label(colon_s$nodes) = &quot;Lymph nodes involved&quot;
explanatory = c(&quot;age&quot;, &quot;sex.factor&quot;, 
  &quot;extent.factor&quot;, &quot;nodes&quot;)

colon_s %>% 
  summary_factorlist(dependent, explanatory, 
  p=TRUE, na_include=TRUE, 
  add_dependent_label=TRUE) -> table1
table1</pre>

<pre>Dependent: Differentiation                            Well    Moderate       Poor      p
                Age (years)           Mean (SD) 60.2 (12.8) 59.9 (11.7)  59 (12.8)  0.788
                        Sex              Female   51 (11.6)  314 (71.7)  73 (16.7)  0.400
                                           Male    42 (9.0)  349 (74.6)  77 (16.5)       
           Extent of spread           Submucosa    5 (25.0)   12 (60.0)   3 (15.0)  0.081
                                         Muscle   12 (11.8)   78 (76.5)  12 (11.8)       
                                         Serosa   76 (10.2)  542 (72.8) 127 (17.0)       
                            Adjacent structures     0 (0.0)   31 (79.5)   8 (20.5)       
       Lymph nodes involved           Mean (SD)   2.7 (2.2)   3.6 (3.4)  4.7 (4.4) &lt;0.001</pre>

<h2>Logistic regression table</h2>
<p>Now examine explanatory variables against outcome. Check plot runs ok.</p>
<pre>explanatory = c(&quot;age&quot;, &quot;sex.factor&quot;, 
  &quot;extent.factor&quot;, &quot;nodes&quot;, 
  &quot;differ.factor&quot;)
dependent = &quot;mort_5yr&quot;
colon_s %>% 
  finalfit(dependent, explanatory, 
  dependent_label_prefix = &quot;&quot;) -> table2</pre>

<pre>Mortality 5 year                           Alive        Died           OR (univariable)         OR (multivariable)
          Age (years)           Mean (SD) 59.8 (11.4) 59.9 (12.5)  1.00 (0.99-1.01, p=0.986)  1.01 (1.00-1.02, p=0.195)
                  Sex              Female  243 (47.6)  194 (48.0)                          -                          -
                                     Male  268 (52.4)  210 (52.0)  0.98 (0.76-1.27, p=0.889)  0.98 (0.74-1.30, p=0.885)
     Extent of spread           Submucosa    16 (3.1)     4 (1.0)                          -                          -
                                   Muscle   78 (15.3)    25 (6.2)  1.28 (0.42-4.79, p=0.681)  1.28 (0.37-5.92, p=0.722)
                                   Serosa  401 (78.5)  349 (86.4) 3.48 (1.26-12.24, p=0.027) 3.13 (1.01-13.76, p=0.076)
                      Adjacent structures    16 (3.1)    26 (6.4) 6.50 (1.98-25.93, p=0.004) 6.04 (1.58-30.41, p=0.015)
 Lymph nodes involved           Mean (SD)   2.7 (2.4)   4.9 (4.4)  1.24 (1.18-1.30, p&lt;0.001)  1.23 (1.17-1.30, p&lt;0.001)
      Differentiation                Well   52 (10.5)   40 (10.1)                          -                          -
                                 Moderate  382 (76.9)  269 (68.1)  0.92 (0.59-1.43, p=0.694)  0.70 (0.44-1.12, p=0.132)
                                     Poor   63 (12.7)   86 (21.8)  1.77 (1.05-3.01, p=0.032)  1.08 (0.61-1.90, p=0.796)</pre>

<h2>Odds ratio plot</h2>

<pre>colon_s %>% 
  or_plot(dependent, explanatory, 
  breaks = c(0.5, 1, 5, 10, 20, 30))</pre>

<p><a rel="nofollow" href="https://i1.wp.com/www.datasurg.net/wp-content/uploads/2018/05/example_or_plot.png" target="_blank"><img data-orig-file="https://i1.wp.com/www.datasurg.net/wp-content/uploads/2018/05/example_or_plot.png?fit=1170%2C443" data-orig-size="1170,443" data-medium-file="https://i1.wp.com/www.datasurg.net/wp-content/uploads/2018/05/example_or_plot.png?fit=300%2C114" data-attachment-id="991" data-image-meta="{" data-image-description="" src="https://i1.wp.com/www.datasurg.net/wp-content/uploads/2018/05/example_or_plot.png?resize=525%2C199" data-permalink="http://www.datasurg.net/2018/05/22/finalfit-knitr-and-r-markdown-for-quick-results/example_or_plot/" data-large-file="https://i1.wp.com/www.datasurg.net/wp-content/uploads/2018/05/example_or_plot.png?fit=525%2C199" alt="" data-image-title="example_or_plot" sizes="(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px" width="450" data-comments-opened="1" class="wp-image-991" data-recalc-dims="1"></a></p>
<h2>To MS Word via knitr/R Markdown</h2>
<p>Important. In most R Markdown set-ups, environment objects require to be saved and loaded to R Markdown document.</p>
<pre># Save objects for knitr/markdown
save(table1, table2, dependent, explanatory, file = &quot;out.rda&quot;)</pre>
<p>We use RStudio Server Pro set-up on Ubuntu. But these instructions should work fine for most/all RStudio/Markdown default set-ups.</p>
<p>In RStudio, select <code>File > New File > R Markdown</code>.</p>
<p>A useful template file is produced by default. Try hitting <code>knit to Word</code> on the <code>knitr</code> button at the top of the <code>.Rmd</code> script window. </p>
<p>Now paste this into the file:</p>
<pre>---
title: &quot;Example knitr/R Markdown document&quot;
author: &quot;Ewen Harrison&quot;
date: &quot;22/5/2018&quot;
output:
  word_document: default
---

```{r setup, include=FALSE}
# Load data into global environment. 
library(finalfit)
library(dplyr)
library(knitr)
load(&quot;out.rda&quot;)
```

## Table 1 - Demographics
```{r table1, echo = FALSE, results='asis'}
kable(table1, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;))
```

## Table 2 - Association between tumour factors and 5 year mortality
```{r table2, echo = FALSE, results='asis'}
kable(table2, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;))
```

## Figure 1 - Association between tumour factors and 5 year mortality
```{r figure1, echo = FALSE}
colon_s %>% 
  or_plot(dependent, explanatory)
```</pre>

<p><a rel="nofollow" href="http://www.datasurg.net/wp-content/uploads/2018/05/example.docx" target="_blank">It’s ok, but not great.</a></p>
<h3>Create Word template file</h3>
<p>Now, edit the Word template. Click on a table. The <code>style</code> should be <code>compact</code>. Right click > <code>Modify... > font size = 9</code>. Alter heading and text styles in the same way as desired. Save this as <code>template.docx</code>. Upload to your project folder. Add this reference to the <code>.Rmd</code> YAML heading, as below. Make sure you get the space correct. </p>
<p>The plot also doesn’t look quite right and it prints with warning messages. Experiment with <code>fig.width</code> to get it looking right. </p>
<p>Now paste this into your <code>.Rmd</code> file and run:</p>

<pre>---
title: &quot;Example knitr/R Markdown document&quot;
author: &quot;Ewen Harrison&quot;
date: &quot;21/5/2018&quot;
output:
  word_document:
    reference_docx: template.docx  
---

```{r setup, include=FALSE}
# Load data into global environment. 
library(finalfit)
library(dplyr)
library(knitr)
load(&quot;out.rda&quot;)
```

## Table 1 - Demographics
```{r table1, echo = FALSE, results='asis'}
kable(table1, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;))
```

## Table 2 - Association between tumour factors and 5 year mortality
```{r table2, echo = FALSE, results='asis'}
kable(table2, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;))
```

## Figure 1 - Association between tumour factors and 5 year mortality
```{r figure1, echo = FALSE, warning=FALSE, message=FALSE, fig.width=10}
colon_s %>% 
  or_plot(dependent, explanatory)
```</pre>

<p><a rel="nofollow" href="http://www.datasurg.net/wp-content/uploads/2018/05/example2.docx" target="_blank">This is now looking good for me, and further tweaks can be made. </a></p>
<h2>To PDF via knitr/R Markdown</h2>
<p>Default settings for PDF:</p>

<pre>---
title: &quot;Example knitr/R Markdown document&quot;
author: &quot;Ewen Harrison&quot;
date: &quot;21/5/2018&quot;
output:
  pdf_document: default
---

```{r setup, include=FALSE}
# Load data into global environment. 
library(finalfit)
library(dplyr)
library(knitr)
load(&quot;out.rda&quot;)
```

## Table 1 - Demographics
```{r table1, echo = FALSE, results='asis'}
kable(table1, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;))
```

## Table 2 - Association between tumour factors and 5 year mortality
```{r table2, echo = FALSE, results='asis'}
kable(table2, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;))
```

## Figure 1 - Association between tumour factors and 5 year mortality
```{r figure1, echo = FALSE}
colon_s %>% 
  or_plot(dependent, explanatory)
```</pre>

<p>Again, ok but not great.<br>
<iframe src="http://docs.google.com/viewer?url=http%3A%2F%2Fwww.datasurg.net%2Fwp-content%2Fuploads%2F2018%2F05%2Fexample.pdf&hl=en_GB&embedded=true"></iframe>
</p>
<p>We can fix the plot in exactly the same way. But the table is off the side of the page. For this we use the <code>kableExtra</code> package. Install this in the normal manner. You may also want to alter the margins of your page using <code>geometry</code> in the preamble. </p>

<pre>---
title: &quot;Example knitr/R Markdown document&quot;
author: &quot;Ewen Harrison&quot;
date: &quot;21/5/2018&quot;
output:
  pdf_document: default
geometry: margin=0.75in
---

```{r setup, include=FALSE}
# Load data into global environment. 
library(finalfit)
library(dplyr)
library(knitr)
library(kableExtra)
load(&quot;out.rda&quot;)
```

## Table 1 - Demographics
```{r table1, echo = FALSE, results='asis'}
kable(table1, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;),
						booktabs=TRUE)
```

## Table 2 - Association between tumour factors and 5 year mortality
```{r table2, echo = FALSE, results='asis'}
kable(table2, row.names=FALSE, align=c(&quot;l&quot;, &quot;l&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;, &quot;r&quot;),
			booktabs=TRUE) %>% 
	kable_styling(font_size=8)
```

## Figure 1 - Association between tumour factors and 5 year mortality
```{r figure1, echo = FALSE, warning=FALSE, message=FALSE, fig.width=10}
colon_s %>% 
  or_plot(dependent, explanatory)
```</pre>

<p>This is now looking pretty good for me as well.<br>
<iframe src="http://docs.google.com/viewer?url=http%3A%2F%2Fwww.datasurg.net%2Fwp-content%2Fuploads%2F2018%2F05%2Fexample2.pdf&hl=en_GB&embedded=true"></iframe>
</p>
<p>There you have it. A pretty quick workflow to get final results into Word and a PDF.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.datasurg.net/2018/05/22/finalfit-knitr-and-r-markdown-for-quick-results/"> R – DataSurg</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/RZ9PCnhis4M" height="1"></a></div>