I know I can easily write one, but does anyone know if stringr (or stringi) already has a function that concatenates a vector of one or more words separated by commas, but with an "and" before the last word?
Asked
Active
Viewed 210 times
2 Answers
8
You can use the knitr::combine_words
function
knitr::combine_words(letters[1:2])
# [1] "a and b"
knitr::combine_words(letters[1:3])
# [1] "a, b, and c"
knitr::combine_words(letters[1:4])
# [1] "a, b, c, and d"

MrFlick
- 195,160
- 17
- 277
- 295
-
Thanks a lot. I'm surprised this function isn't also in stringr – code_cowboy May 10 '19 at 18:46
2
Here's another solution :
enum <- function(x)
paste(c(head(x,-2), paste(tail(x,2), collapse = ", and ")), collapse = ", ")
enum(letters[1])
#> [1] "a"
enum(letters[1:2])
#> [1] "a, and b"
enum(letters[1:3])
#> [1] "a, b, and c"
enum(letters[1:4])
#> [1] "a, b, c, and d"
Created on 2019-05-11 by the reprex package (v0.2.1)

moodymudskipper
- 46,417
- 11
- 121
- 167