Simple way to output list in the style "V, W, X, Y, and Z" in R

formatting, r, r-markdown, string

Solution

This is one of the helpful tools in the pander package

pander::p

p merges elements of a vector in one string for the sake of pretty inline printing. Default parameters are read from appropriate option values (see argument description for details). This function allows you to put the results of an expression that yields a variable inline, by wrapping the vector elements with the string provided in wrap, and separating elements by main and ending separator (sep and copula). In case of a two-length vector, value specified in copula will be used as a separator. You can also control the length of provided vector by altering an integer value specified in limit argument (defaults to Inf).

example:

devtools::install_github('Rapporter/pander')
## also available on cran:
# install.packages('pander')

library(pander)

p(levels(iris$Species), wrap = '')
# "setosa, versicolor and virginica"

p(levels(iris$Species), wrap = '', copula = ', and ')
# "setosa, versicolor, and virginica"

Problem

When using `rmarkdown` it is frequently the case that you want to programmatically generate fragments of text, in particular to list items being used. For example; ``` The species of iris examined were `r cat(as.character(unique(iris$Species)), sep = ", ")`. ``` Which would produce The species of iris examined were setosa, versicolor, virginica. To read properly it should be The species of iris examined were setosa, versicolor, and virginica. Is there a simple way to do this?

Original source