Skip to content

Instantly share code, notes, and snippets.

@randrescastaneda
Last active April 1, 2020 12:14
Show Gist options
  • Save randrescastaneda/46331383301265ced2de4aa478c6c6b8 to your computer and use it in GitHub Desktop.
Save randrescastaneda/46331383301265ced2de4aa478c6c6b8 to your computer and use it in GitHub Desktop.
Add "and" to character vector to be used in string contexts such as Rmarkdown documents
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment