stringr 函数连接由逗号分隔的单词向量,在最后一个单词之前使用 "and"

stringr function to concatenate vector of words separated by comma with "and" before last word

我知道我可以轻松地写一个,但是有谁知道 stringr(或 stringi)是否已经有一个函数连接一个或多个用逗号分隔的单词的向量,但在 "and" 之前遗言?

您可以使用knitr::combine_words函数

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"

这是另一个解决方案:

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"

reprex package (v0.2.1)

创建于 2019-05-11