gpt4 book ai didi

R:删除字符串开头和结尾的数字

转载 作者:行者123 更新时间:2023-12-04 22:04:37 25 4
gpt4 key购买 nike

我有以下向量:

words <- c("5lang","kasverschil2","b2b")

我要删除 "5""5lang""2""kasverschil2" .但我不想删除 "2""b2b" .

最佳答案

 gsub("^\\d+|\\d+$", "", words)    
#[1] "lang" "kasverschil" "b2b"

另一种选择是使用 stringi
 library(stringi)
stri_replace_all_regex(words, "^\\d+|\\d+$", "")
#[1] "lang" "kasverschil" "b2b"

此处使用 OP 提供的数据集的变体是 3 个主要解决方案的基准测试(请注意,这些字符串非常短且人为设计;结果在更大的真实数据集上可能会有所不同):
words <- rep(c("5lang","kasverschil2","b2b"), 100000)

library(stringi)
library(microbenchmark)

GSUB <- function() gsub("^\\d+|\\d+$", "", words)
STRINGI <- function() stri_replace_all_regex(words, "^\\d+|\\d+$", "")
GREGEXPR <- function() {
gregexpr(pattern='(^[0-9]+|[0-9]+$)', text = words) -> mm
sapply(regmatches(words, mm, invert=TRUE), paste, collapse="")
}

microbenchmark(
GSUB(),
STRINGI(),
GREGEXPR(),
times=100L
)

## Unit: milliseconds
## expr min lq median uq max neval
## GSUB() 301.0988 349.9952 396.3647 431.6493 632.7568 100
## STRINGI() 465.9099 513.1570 569.1972 629.4176 738.4414 100
## GREGEXPR() 5073.1960 5706.8160 6194.1070 6742.1552 7647.8904 100

关于R:删除字符串开头和结尾的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com