I looked but failed to find an answer to how to add a character to the end of each and every element in a string vector in R, except the last one...
Consider the following:
data <- c("cat", "dog", "mouse", "lion")
I'd like to apply a function that pastes a "," at the end of each element such that the result is:
[1] "cat,", "dog,", "mouse,", "lion"
apply functions? for loop? any help is appreciated...
You can do this in a couple of ways:
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)], ',')
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
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