在r中以不同方式替换字符串中的多个符号

Replace multiple symbols in a string differently in r

我尝试使用 gsub 将 (5,10](20,20] 等值重新编码为 5-10%20-20%。所以,第一个括号应该消失,逗号应该改为破折号,最后一个括号应该是 %。我能做的只有

x<-c("(5,10]","(20,20]")
gsub("\,","-",x)

然后逗号改为短划线。我怎样才能改变其他人呢?

谢谢。

保持简单,一组 gsub。

x <- c("(5,10]","(20,20]")
x <- gsub(",", "-", x) # remove comma
x <- gsub("\(", "", x) # remove bracket
x <- gsub("]", "%", x) # replace ] by %
x
 "5-10%"  "20-20%"

这是另一种选择:

> gsub("\((\d+),(\d+)\]", "\1-\2%", x)
[1] "5-10%"  "20-20%"

其他解决方案。

我们使用 regmatches 提取所有数字。然后我们合并每个第一个和第二个数字。

nrs <- regmatches(x, gregexpr("[[:digit:]]+", x))
nrs <- as.numeric(unlist(nrs))
i <- 1:length(nrs); i <- i[(i%%2)==1]
for(h in i){print(paste0(nrs[h],'-',nrs[h+1],'%'))}

[1] "5-10%"
[1] "20-20%"

纯属娱乐,丑陋的一行字:

sapply(regmatches(x, gregexpr("\d+", x)), function(x) paste0(x[1], "-", x[2], "%"))

[1] "5-10%"  "20-20%"