Insert character at end of string in R, except for the last element

You can do this in a couple of ways:

  1. Subset the 'data' without the last element, paste ,, and assign that to the original data (without last element)

    data[-length(data)] <- paste0(data[-length(data)], ',')
    
  2. Use strsplit after collapsing it as a string

    strsplit(paste(data, collapse=', '), ' ')[[1]]     
    

I know this is an old question, but since I suppose people (like me) still end here, they may want to consider easy solutions offered by more recent but fairly common packages. They offer slightly different options.

Option 1: Knitr

data <- c("cat", "dog", "mouse", "lion")
knitr::combine_words(data, before = '`')

# `cat`, `dog`, `mouse`, and `lion`

Option 2: Glue

data <- c("cat", "dog", "mouse", "lion")
glue::glue_collapse(x = data, ", ", last = " and ")

# cat, dog, mouse and lion

Tags:

R