Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing vector to string - special separator for last element

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
like image 908
Ferroao Avatar asked Sep 20 '25 16:09

Ferroao


2 Answers

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"
like image 101
akrun Avatar answered Sep 22 '25 06:09

akrun


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

like image 20
user1420372 Avatar answered Sep 22 '25 07:09

user1420372