Justify text in R
Well, if there is no built-in way this works well enough for my purposes. Thanks for the comments above about how to use html styling as well.
justify <- function(string, width=getOption('width'),
fill=c('random', 'right', 'left')) {
strs <- strwrap(string, width=width)
paste(fill_spaces(strs, width, match.arg(fill)), collapse="\n")
}
fill_spaces <- function(lines, width, fill) {
tokens <- strsplit(lines, '\\s+')
res <- lapply(head(tokens, -1L), function(x) {
nspace <- length(x)-1L
extra <- width - sum(nchar(x)) - nspace
reps <- extra %/% nspace
extra <- extra %% nspace
times <- rep.int(if (reps>0) reps+1L else 1L, nspace)
if (extra > 0) {
if (fill=='right') times[1:extra] <- times[1:extra]+1L
else if (fill=='left')
times[(nspace-extra+1L):nspace] <- times[(nspace-extra+1L):nspace]+1L
else times[inds] <- times[(inds <- sample(nspace, extra))]+1L
}
spaces <- c('', unlist(lapply(times, formatC, x=' ', digits=NULL)))
paste(c(rbind(spaces, x)), collapse='')
})
c(res, paste(tail(tokens, 1L)[[1]], collapse = ' '))
}
cat(justify(string, width=40))
# Out of the night that covers me, Black
# as the pit from pole to pole, I thank
# whatever gods may be For my
# unconquerable soul. In the fell clutch
# of circumstance I have not winced nor
# cried aloud. Under the bludgeonings of
# chance My head is bloody, but unbow'd.
# Beyond this place of wrath and tears
# Looms but the Horror of the shade, And
# yet the menace of the years Finds and
# shall find me unafraid. It matters not
# how strait the gate, How charged with
# punishments the scroll, I am the master
# of my fate: I am the captain of my
# soul.
Align text inside a plot
While legend() is of course appropriate for legends, there is a general solution for all text. The trick is that the pos option not only sets the position of the text relative to the current location but it also sets justification. Above and Below are center justified. Setting pos to 2 makes the text right justified. When it is set to the right of the position (pos = 4) then it is left justified.
For left justified replace your text code with...
text(1.5, 150, paste("Mean =", round(MyMean, 1), "\nMedian =",
round(MyMedian, 1), "\nStd.Dev =", round(MySd, 1)), pos = 4)
and for right justified...
text(5.0, 150, paste("Mean = ", round(MyMean, 1), "\nMedian = ",
round(MyMedian, 1), "\nStd.Dev = ", round(MySd, 1), sep = ''), pos = 2)
How to justify (to both sides) text in R Markdown when knitting in pdf output
R Markdown should default to using justified text. However, if you only want to export to PDF, we can directly use LaTeX commands within the document.using the standard arguments \centering
\raggedright
and \raggedleft
, as explained here.
Here is a minimal example:
---
output: pdf_document
---
```{r, include = FALSE}
devtools::install_github("coolbutuseless/lipsum")
library(lipsum)
```
**Default**
`r lipsum[1]`
\centering
**Centered Text**
`r lipsum[1]`
\raggedright
**Ragged Right**
`r lipsum[1]`
\raggedleft
**Ragged Left**
`r lipsum[1]`
If you want to revert to justified text, you can use the ragged2e
LaTeX package. You will need to load this within the YAML by adding:
---
output: pdf_document
header-includes:
- \usepackage[document]{ragged2e}
---
\raggedleft
**Ragged Left**
`r lipsum[1]`
\justifying
**Revert to Justified**
`r lipsum[1]`
Edit
If you are using the papaja
template you need to include all the YAML. Not providing an author, shorttitle or another other field will cause it to crash.
---
title : "The title"
shorttitle : "Title"
author:
- name : "First Author"
affiliation : "1"
corresponding : yes # Define only one corresponding author
address : "Postal address"
email : "my@email.com"
- name : "Ernst-August Doelle"
affiliation : "1,2"
affiliation:
- id : "1"
institution : "Wilhelm-Wundt-University"
- id : "2"
institution : "Konstanz Business School"
author_note: |
Add complete departmental affiliations for each author here. Each new line herein must be indented, like this line.
Enter author note here.
abstract: |
Enter abstract here. Each new line herein must be indented, like this line.
keywords : "keywords"
wordcount : "X"
bibliography : ["r-references.bib"]
figsintext : no
figurelist : no
tablelist : no
footnotelist : no
lineno : yes
mask : no
class : "man"
output : papaja::apa6_pdf
header-includes:
- \usepackage[document]{ragged2e}
---
```{r load_packages, include = FALSE}
library(lipsum)
```
\justifying
**Default**
`r lipsum[1]`
Is there a way to Justify the text on R Markdown?
ClaudiaDL,
I've included a video and some articles I found on RStudio regarding how to setup a refrence docx for the styles you'd like to use in your RMarkdown document when it outputs to a Word document.
Here is a video on how to set it up: https://vimeo.com/110804387
And here are two more articles on how to do it.
https://bookdown.org/yihui/rmarkdown/word-document.html
https://rmarkdown.rstudio.com/articles_docx.html
Change alignment of plot text
Alignment (adjustment / justification) of text
is set by the adj
argument. To left-align, set adj = 0
.
From ?text
:
adj
: one or two values in [0, 1] which specify the x (and optionally y) adjustment (‘justification’) of the labels, with 0 for left/bottom, 1 for right/top, and 0.5 for centered. On most devices values outside [0, 1] will also work.
adj
allows adjustment of the text position with respect to(x, y)
. Values of 0, 0.5, and 1 specify that(x, y)
should align with the left/bottom, middle and right/top of the text, respectively. The default is for centered text, i.e.,adj = c(0.5, NA)
. Accurate vertical centering needs character metric information on individual characters which is only available on some devices. Vertical alignment is done slightly differently for character strings and for expressions:adj = c(0,0)
means to left-justify and to align on the baseline for strings but on the bottom of the bounding box for expressions. This also affects vertical centering: for strings the centering excludes any descenders whereas for expressions it includes them. UsingNA
for strings centers them, including descenders.
plot(1:10, 1:10)
text(x = 6, y = 1, "text", adj = 0)
adj = 0
will left-align the text:
Can I justify my text when I create a docx file with Quarto?
I just solved with https://quarto.org/docs/output-formats/ms-word-templates.html
First you create a reference .docx and define the style of your document, like title, author, first paragraph, etc.
Than you add at your .qmd
format:
docx:
reference-doc: custom-reference-doc.docx
R: fully justified of strwrap
This is a standard plotting parameter described on the help page ?par
. For left justification, you need the parameter adj = 0
plot(rnorm(100), main = paste(
strwrap(
'This is a very long title wrapped on multiple lines without the need to adjust it by hand',
width = 50), collapse = "\n" ), adj=0)
For right justified, use adj=1
.
Related Topics
Print R-Squared for All of the Models Fit with Lmlist
Downloading Files from Ftp with R
How to Reverse Legend (Labels and Color) So High Value Starts at Bottom
How to Transpose a Tibble() in R
Draw a Trend Line Using Ggplot
Produce a Table Spanning Multiple Pages Using Kable()
How to Create an Infix %Between% Operator
Change a Column from Birth Date to Age in R
Extract Name of Data.Frame in R as Character
Replace a Subset of a Data Frame with Dplyr Join Operations
Intersecting Points and Polygons in R
R Plots: How to Draw a Border, Shadow or Buffer Around Text Labels
R - Cumulative Sum by Condition
How to Speed Up or Vectorize a for Loop