Add "and" at the end of character vector

Imagine you’re writing in an Rmarkdown document and you need to list a series of items in your text. Also, the elements you want to include in your text are stored in a vector, say cvec, so you just need to include the vector as part of the text in your rmarkdown document. However, you realize that the last item is not separated by an “and” in the text, so your text does not read well.

The function below solves that problem for you.

add_and <- function(x) {
  if (!(is.character(x))) {
    warning("`x` must be character. coercing to character")
    x <- as.character(x)
  }

  lx <- length(x)
  if (lx == 1) {
    y <- x
  }
  else if (lx == 2) {
    y <- paste(x[1], "and", x[2])
  }
  else {
    y <- c(x[1:lx-1], paste("and", x[lx]))
    y <- paste(y, collapse = ", ")
  }
  return(y)
}

cvec <- c("faith", "family", "purpose")
add_and(cvec)
## [1] "faith, family, and purpose"
cvec <- c("faith", "family")
add_and(cvec)
## [1] "faith and family"
cvec <- c("faith")
add_and(cvec)
## [1] "faith"

If you want to contribute to this function, you can do it in this gist

Economist/Data Scientist

My research interests include … matter.