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

橙三吉。 提交于 2019-12-02 05:46:39

问题


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?


回答1:


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"



回答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)



来源:https://stackoverflow.com/questions/56081473/stringr-function-to-concatenate-vector-of-words-separated-by-comma-with-and-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!