I'm trying to concatenate elements of a dynamically changing vector with commas and "and" as separators in a string. The problem is, when the character vector has only one element, I have an unwanted "and" before the string.
vec <-c("something")
vec <-c("something","something")
vec <-c("something","something","something")
paste0(c(paste(head(vec, n=length(vec) -1), collapse = ", ") ,
"and", paste(tail(vec, n=1) )
),
collapse= " ")
[1] " and something" # not what is expected
[1] "something and something" # ok
[1] "something, something and something" #ok
We can use sub
with paste
fPaste <- function(vec) sub(",\\s+([^,]+)$", " and \\1", toString(vec))
fPaste("something")
#[1] "something"
fPaste(c("something","something"))
#[1] "something and something"
fPaste(c("something","something","something") )
#[1] "something, something and something"
fPaste(c("something","something","something", "something") )
#[1] "something, something, something and something"
I had previously used an(other) existing function but can't remember which one, but this works perfectly and I always use knitr! Hoping I remember it in future.
knitr::combine_words(c("something"))
something
knitr::combine_words(c("something","something"))
something and something
knitr::combine_words(c("something","something","something"))
something, something, and something
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With