在字符串的最后一个元素之前插入“and”

luc*_*ano 4 string text r

假设我有这个字符串:

fruits <- c("apple", "pear", "orange", "banana", "melon")
Run Code Online (Sandbox Code Playgroud)

我可以将每个元素折叠成一个字符串,如下所示:

cat(paste(fruits, collapse = ", "))
Run Code Online (Sandbox Code Playgroud)

但是如何在最后一个元素之前插入 and 呢?请注意,我的真实字符串长度有所不同。

输出应该是:

apple, pear, orange, banana and melon
Run Code Online (Sandbox Code Playgroud)

Avi*_*Raj 6

您可以使用子

> cat(sub("(.*),", "\\1 and",paste(fruits, collapse = ", ")))
apple, pear, orange, banana and melon
Run Code Online (Sandbox Code Playgroud)