Reputation: 121
When working in R Markdown, I typically add text outside of a chunk (e.g., figure/tables headings) but in this case I need to loop through 50+ variables to create a couple plots specific to each variable. Hence, I'm adding a few lines of text within the code chunk so that it is included with each set of plots. Ideally, I'd also like to add a page break before moving on to the next variable as well. I'm knitting to Word (this is the format that has been requested of me).
I've tried adding spaces after each line, "/newline", "/n", without success (I've tried with one backslash and two, as I wasn't clear which to use for a Word doc). I could just edit the document manually but that kind of defeats the purpose! Any tips would be appreciated.
```{r create plots, echo=FALSE, fig.height=8, fig.width=8, results='asis'}
for (i in seq(1, nrow(variables))) {
x <- variables[i,]
x <- drop.levels(x)
var <- x$variables
# Add some text
cat("Variable: **", paste(var), "** (N = ", number obs, ")", sep="")
cat("\n")
cat("More Text")
cat("\n")
cat("Even more text")
# Create plots.....
# insert page break
cat("\pagebreak")
}
```
Upvotes: 8
Views: 14650
Reputation: 59
The easiest way add a break line is:
cat('<br>')
So, in your example:
# Add some text
cat("Variable: **", paste(var), "** (N = ", number obs, ")", sep="")
cat('<br>')
cat("More Text")
cat('<br>')
cat("Even more text")
Upvotes: 0
Reputation: 58
This simple solution works for me:
comment=NA
to suppress the hashtags in your chunk.In the example below,
blanks <- rep(c(' ', '\n'),5)
has a first term that looks like a blank space' '
. However, between the single quotes, the space was actually created by typing the keystroke shortcut,[CTRL]+ 255
. In your markdown document, the inserted character will appear as a single dot, highlighted in pink.
Here's some sample code:
blanks <- rep(c(' ', '\n'),5) # This will print five blank lines between plots.
AddBreak <- function() {
for (i in blanks)
cat(i)
}
p1 <- plot(data.frame(a = seq(1,16,by=1), b = sample(10:20,16, replace = TRUE)), main="Plot 1")
p2 <- plot(data.frame(a = seq(1,16,by=2), b = sample(10:20,8, replace = TRUE)), main="Plot 2")
p3 <- plot(data.frame(a = seq(1,32,by=1), b = sample(10:20,32, replace = TRUE)), main="Plot 3")
p1
AddBreak()
p2
AddBreak()
p3
Upvotes: 0
Reputation: 1902
After following the directions at How to add a page break in word document generated by RStudio & markdown to create the reference_docx, this seems to do what you want
---
output:
word_document:
reference_docx: headingfive.docx
---
```{r, results="asis"}
for (var in LETTERS[1:6]){
# Add some text
cat("Variable: **", paste(var), "**", sep="")
cat(" \n")
cat("More Text")
cat(" \n")
cat("Even more text")
cat(" \n")
# Create plots.....
# insert page break
cat("\n")
cat("#####\n")
cat("\n")
}
```
The extra "\n" at the end of the level 5 heading, and before/after, are important.
Upvotes: 8