Achal Neupane
Achal Neupane

Reputation: 5719

Insert a character at every nth instance in R

I have a vector called myvec<- (c(141,143,139,139,140,141,138,140,142,138)). How can I insert Y every n=3 instance of ,?

The result I want is: 141,143,139Y139,140,141Y138,140,142

Upvotes: 3

Views: 654

Answers (1)

akrun
akrun

Reputation: 887691

May be we need

gsub("([^,]+,[^,]+,[^,]+),", "\\1Y", paste(myvec, collapse=","))

To make this more generalizable, the pattern can be created with strrep and sprintf

createPattern <- function(n) {
   sprintf("(%s[^,]+),", strrep("[^,]+,", n-1))
 }

pat <- createPattern(3)
gsub(pat, "\\1Y", paste(myvec, collapse=","))

Upvotes: 4

Related Questions