简体   繁体   中英

How can you increment a gsub() replacement string?

Assume a data frame has many columns that all say “bonus”. The goal is to rename each bonus column uniquely with an appended number. Example data:

string  <- c("bonus", "bonus", "bonus", "bonus")
string
[1] "bonus" "bonus" "bonus" "bonus"

Desired column name output:

[1] "bonus1" "bonus2" "bonus3" "bonus4"

Assume you don't know how many bonus columns there are be so you cannot simply paste from 1 to that number of columns to each bonus column name.

The following approach works but seems inelegant and seems too hard-coded:

bonus.count  <- nrow(count(grep(pattern = "bonus", x = string)))
string.numbered  <- paste0(string, seq(from = 1, to = bonus.count, 1)

How can the gsub function (or another regex-based function) substitute an incremented number? Along the lines of

string.gsub.numbered  <- gsub(pattern = "bonus", replacement = "bonusincremented by one until no more bonuses", x = string)

As far as I know, gsub can't run any sort of function over each result, but using regexpr and regmatches makes this pretty easy

string  <- c("bonus", "bonus", "bonus", "bonus")
m <- regexpr("bonus",string)
regmatches(string,m) <- paste0(regmatches(string,m), 1:length(m))
string
# [1] "bonus1" "bonus2" "bonus3" "bonus4"

The nice part is that regmatches allows for assignment so it's easy to swap out the matched values.

1) Using string defined in the question we can write:

paste0(string, seq_along(string))

2) If what you really have is something like this:

string2 <- "As a bonus we got a bonus coupon."

and you want to change that to "As a bonus1 we got a bonus2 coupon." then gsubfn in the gsubfn package can do that. Below, the fun method of the p proto object will be applied to each occurrence of "bonus" with count automatically incremented. THe proto object p automatically saves the state of count between matches to allow this:

library(gsubfn)
string2 <- "As a bonus we got a bonus coupon." # test data

p <- proto(fun = function(this, x) paste0(x, count))
gsubfn("bonus", p, string2)

giving:

[1] "As a bonus1 we got a bonus2 coupon."

There are additional exxamples in the proto vignette .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM