Home > other >  `gsub`: replace match in R
`gsub`: replace match in R

Time:04-07

I have a character vector with several strings, e.g.,

"as.factor(p15)   index_magt lag_kemner_pct log_indb"

I'm trying to use gsub to replace "as.factor(p15) index_magt" with "p15_magt" using the following code:

vector <- c("as.factor(p15)   index_magt lag_kemner_pct log_indb", "as.factor(p40)   index_magt lag_kemner_pct venstrepar_pct")
    
vector <- gsub("as.factor(15)   index_magt","p15_magt", vector)

However, this yields the following result:

 vector
 [1] "as.factor(p15)   index_magt lag_kemner_pct log_indb"

I also tried:

vector <- gsub("as\\.factor\\(15\\) \\  index_magt","p15_magt", vector)

Does anyone have a solution? I need the expression to match the number 15 in "as.factor(15)" precisely, and not just use [[:alnum:]] for any number. I have been struggling for some time :/

CodePudding user response:

I think you just missed a "p" in front of "15" in your gsub call:

vector <- gsub("as\\.factor\\(p15\\) \\  index_magt","p15_magt", vector)

> vector
[1] "p15_magt lag_kemner_pct log_indb"                          "as.factor(p40)   index_magt lag_kemner_pct venstrepar_pct"

CodePudding user response:

You need to use escaping:

x <- "as.factor(p15)   index_magt lag_kemner_pct log_indb"

gsub("as\\.factor\\(p15\\) \\  index_magt", "p15_magt", x)

Alternatively, use just sub iff there's just one match per string; also, you don't have to escape .:

sub("as.factor\\(p15\\) \\  index_magt", "p15_magt", x)
  • Related