Skip to content

Instantly share code, notes, and snippets.

@arraytools
Last active December 27, 2023 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arraytools/4f182b036ae7f95a31924ba5d5d3f069 to your computer and use it in GitHub Desktop.
Save arraytools/4f182b036ae7f95a31924ba5d5d3f069 to your computer and use it in GitHub Desktop.
A demonstration of using the 'officer' R package
---
title: "Officer"
output: html_document
date: "2023-12-26"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officer)
library(flextable)
library(survival)
library(ggplot2)
```
```{r officer, echo=FALSE}
foo <- function(fit) {
plot(fit, lty = 1:2, main = "KM curves", col=1:2)
}
doc <- read_docx()
ft <- flextable(head(mtcars[, 1:4]))
ft <- set_caption(ft, caption = "Table 1")
ft <- autofit(ft)
doc <- body_add_par(doc, "Section 1", style = "heading 1")
doc <- body_add_flextable(doc, ft)
doc <- body_add_par(doc, "Hello world!", style = "centered")
doc <- body_add_par(doc, "Hello world 2!", style = "Normal")
doc <- body_add_par(doc, "Section 1.1", style = "heading 2")
fit <- survfit(Surv(time, status) ~ x, data = aml)
doc <- body_add_plot(doc, value = foo(fit), style = "centered")
doc <- body_add_break(doc)
doc <- body_add_par(doc, "Section 2", style = "heading 1")
gg_plot <- ggplot(data = iris) +
geom_point(mapping = aes(Sepal.Length, Petal.Length)) +
ggtitle("My ggplot") +
theme(plot.title = element_text(hjust = 0.5))
doc <- body_add_gg(doc, value = gg_plot, style = "centered")
print(doc, target = "officer.docx")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment