user1751679
user1751679

Reputation: 95

R: Using gsub to replace a digit matched by pattern (n) with (n-1) in character vector

I am trying to match the last digit in a character vector and replace it with the matched digit - 1. I have believe gsub is what I need to use but I cannot figure out what to use as the 'replace' argument. I can match the last number using:

gsub('[0-9]$', ???, chrvector)

But I am not sure how to replace the matched number with itself - 1.

Any help would be much appreciated.

Thank you.

Upvotes: 1

Views: 635

Answers (2)

akrun
akrun

Reputation: 887431

We can do this easily with gsubfn

library(gsubfn)
gsubfn("([0-9]+)", ~as.numeric(x)-1, chrvector)
#[1] "str97"    "v197exdf"

Or for the last digit

gsubfn("([0-9])([^0-9]*)$", ~paste0(as.numeric(x)-1, y), chrvector2)
#[1] "str97"      "v197exdf"   "v33chr138d"

data

chrvector <- c("str98", "v198exdf")
chrvector2 <-  c("str98", "v198exdf", "v33chr139d")

Upvotes: 3

Sandipan Dey
Sandipan Dey

Reputation: 23109

Assuming the last digit is not zero,

chrvector <- as.character(1:5)
chrvector
#[1] "1" "2" "3" "4" "5"
chrvector <- paste(chrvector, collapse='') # convert to character string

chrvector <- paste0(substring(chrvector,1, nchar(chrvector)-1), as.integer(gsub('.*([0-9])$', '\\1', chrvector))-1)
unlist(strsplit(chrvector, split=''))
# [1] "1" "2" "3" "4" "4"

This works even if you have the last digit zero:

chrvector <- c(as.character(1:4), '0') # [1] "1" "2" "3" "4" "0"
chrvector <- paste(chrvector, collapse='')    
chrvector <- as.character(as.integer(chrvector)-1)
unlist(strsplit(chrvector, split=''))
# [1] "1" "2" "3" "3" "9"

Upvotes: 0

Related Questions