简体   繁体   English

R:使用gsub将字符(n)匹配的数字替换为字符向量中的(n-1)

[英]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. 我试图匹配字符向量中的最后一位数字并将其替换为匹配的数字 - 1.我相信gsub是我需要使用但我无法弄清楚要用什么作为'替换'参数。 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. 但我不知道如何用自己替换匹配的数字 - 1。

Any help would be much appreciated. 任何帮助将非常感激。

Thank you. 谢谢。

We can do this easily with gsubfn 我们可以使用gsubfn轻松完成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")

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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