11# ' Flatten a string
2+ #
3+ # ' @description
4+ # ' `str_flatten()` reduces a character vector to a single string. This is a
5+ # ' summary function because regardless of the length of the input `x`, it
6+ # ' always returns a single string.
27# '
3- # ' Reduce a character vector to a single string. This is a summary function
4- # ' because regardless of the length of the input `x`, it always returns a
5- # ' single string .
8+ # ' `str_flatten_comma()` is a variation designed specifically for flattening
9+ # ' with commas. It automatically recognises if `last` uses the Oxford comma
10+ # ' and handles the special case of 2 elements .
611# '
712# ' @inheritParams str_detect
813# ' @param collapse String to insert between each piece. Defaults to `""`.
1520# ' str_flatten(letters)
1621# ' str_flatten(letters, "-")
1722# '
18- # ' str_flatten(letters[1:4], ", ", ", and ")
23+ # ' str_flatten(letters[1:3], ", ")
24+ # '
25+ # ' # Use last to customise the last component
26+ # ' str_flatten(letters[1:3], ", ", " and ")
27+ # '
28+ # ' # this almost works if you want an Oxford (aka serial) comma
1929# ' str_flatten(letters[1:3], ", ", ", and ")
30+ # '
31+ # ' # but it will always add a comma, even when not necessary
2032# ' str_flatten(letters[1:2], ", ", ", and ")
21- # ' str_flatten(letters[1], ", ", ", and ")
22- # ' str_flatten(letters[0], ", ", ", and ")
33+ # '
34+ # ' # str_flatten_comma knows how to handle the Oxford comma
35+ # ' str_flatten_comma(letters[1:3], ", and ")
36+ # ' str_flatten_comma(letters[1:2], ", and ")
2337str_flatten <- function (string , collapse = " " , last = NULL , na.rm = FALSE ) {
2438 check_string(collapse )
2539 check_string(last , allow_null = TRUE )
@@ -39,3 +53,16 @@ str_flatten <- function(string, collapse = "", last = NULL, na.rm = FALSE) {
3953
4054 stri_flatten(string , collapse = collapse )
4155}
56+
57+ # ' @export
58+ # ' @rdname str_flatten
59+ str_flatten_comma <- function (string , last = NULL , na.rm = FALSE ) {
60+ check_string(last , allow_null = TRUE )
61+ check_bool(na.rm )
62+
63+ # Remove comma if exactly two elements, and last uses Oxford comma
64+ if (length(string ) == 2 && ! is.null(last ) && str_detect(last , " ^," )) {
65+ last <- str_replace(last , " ^," , " " )
66+ }
67+ str_flatten(string , " , " , last = last , na.rm = na.rm )
68+ }
0 commit comments