Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 972
Corvus Avatar asked Jul 04 '14 22:07

Corvus


1 Answers

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"
like image 167
rawr Avatar answered Oct 02 '22 16:10

rawr