I would like to export output from R console to word and get nicely aligned everything like showed in R console.
I have read that I have to create some kind of word template.doc or template.docx to achieve this.
I do not know how to do it and to which elements of this creation of that template I must pay special attention to.
library(officer)
library(broom)
set.seed(1000)
my_data <- rbind(
data.frame(time = "Pre", treatment = "Control", response = rnorm(100, mean=1)),
data.frame(time = "Pre", treatment = "Treatment", response = rnorm(100, mean=2)),
data.frame(time = "Post", treatment = "Control", response = rnorm(100, mean=1)),
data.frame(time = "Post", treatment = "Treatment", response = rnorm(100, mean=2))
) %>% mutate(time = factor(time, levels = c("Pre", "Post"))) %>%
mutate(treatment = factor(treatment, levels = c("Control", "Treatment")))
model3 <- lm(response ~ time * treatment, data = my_data)
docx <- read_docx()
z5 <- capture.output(kableExtra::kable(tidy(model3)))
z5 <- as.data.frame(z5)
docx <- to_docx(docx, z5, "Title 1", "Subtitle 1")
fn <- tempfile(fileext = ".docx")
print(docx, fn)
gives me firstly this:
and also secondly this:
Everything here is misaligned in word and will require a lot of tweaking. I hope this could be avoided and look nicely and straight in word at once. My second question is how to create that temp file called "fn" in my working directory because this is saved and deeply hidden in Local\Temp etc. long file path.
I would be grateful for help and for explaining all the necessary steps involved it that process especially in creating that word template in order not messing anything in my word present settings.


While following is deviating from
{officer}, this is how I'd get raw Markdown pipe table (console output ofkableExtra::kable(tidy(model3))) and its render to Word / docx with Quarto:Renders as: