Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert "and" before last element in string

Tags:

string

text

r

Say I have this string:

fruits <- c("apple", "pear", "orange", "banana", "melon")

I can collapse each element into a string like this:

cat(paste(fruits, collapse = ", "))

But how can I insert and before the last element? Note that my real strings vary in length.

Output should be:

apple, pear, orange, banana and melon
like image 963
luciano Avatar asked Oct 15 '25 07:10

luciano


1 Answers

You may use sub

> cat(sub("(.*),", "\\1 and",paste(fruits, collapse = ", ")))
apple, pear, orange, banana and melon
like image 148
Avinash Raj Avatar answered Oct 17 '25 22:10

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!