How do you justify text in R? By justify I mean that each line in a paragraph is exactly the same length (like when you justify in open office or excel). I have tried to find an option with strwrap
and cat
but have been unsuccessful.
## Get some sample text example from wikipedia api
library(httr)
library(xml2)
name <- "Invictus"
url <- URLencode(sprintf("https://en.wikisource.org/w/api.php?action=parse&prop=text&page=%s&format=json", name))
res <- read_html(content(GET(url))$parse$text[[1]])
string <- iconv(xml_text(xml_find_all(res, "//p"), trim=TRUE), "latin1", "ASCII", sub=" ")[1:2]
(string <- trimws(gsub('\\n|\\s{3,}', ' ', paste(string, collapse=" "))))
# [1] "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."
Some attempts using the aforementioned functions
## Using these I can get left/right/center justified text but not
## justified like in other text editing programs or newspapers.
width <- 30
cat(paste(strwrap(string, width=width), collapse='\n'))
## Or with cat
tokens <- strsplit(string, '\\s+')[[1]] # tokenise to pass to cat
out <- capture.output(cat(tokens, fill=width, sep=" ")) # strings <= width chars
cat(paste(out, collapse='\n'))
<p style='text-align:justify;'>your text here</p>
tagset. See w3schools.com/cssref/pr_text_text-align.asp. If you're trying to do it within the console, I wish you luck, but doubt there's much to help you. – Christogramtext-align: justify
in your css. – Kimi