R:删除字符串中的子字符串

R:删除字符串中的子字符串,r,substring,substitution,R,Substring,Substitution,是否有一种优雅的方法可以根据字符的索引删除字符串中的子字符串 我现在是这样做的: # My data mystring <- "Hello, how are {you} doing?" index_of_substring <- c(16,20) # Pasting two substrings mystring_no_substring <- paste0(substr(mystring, 1, index_of_substring[1]-1), substr(mystri

是否有一种优雅的方法可以根据字符的索引删除字符串中的子字符串

我现在是这样做的:

# My data
mystring <- "Hello, how are {you} doing?"
index_of_substring <- c(16,20)

# Pasting two substrings
mystring_no_substring <- paste0(substr(mystring, 1, index_of_substring[1]-1), substr(mystring, index_of_substring[2]+1, nchar(mystring)))

# Cleaning extra spaces
mystring_no_substring <- gsub("  ", " ", mystring_no_substring)
#我的数据

mystring您也可以像这样使用
paste0
substr
:-

paste0(substr(mystring, 1, 14), substr(mystring, 21, 27))
1)strsplit/paste将输入拆分为字符,省略16到20之间的字符,将其重新折叠在一起,并用单个空格替换空格。仅使用基函数

gsub(" +", " ", paste(strsplit(s, "")[[1]][-seq(ix[1], ix[2])], collapse = ""))
## [1] "Hello, how are doing?"

2)substr我相信我的解决方案与将您的方法编码为一般函数时得到的结果非常接近,但现在开始。我首先使用一个名为“strpos_fixed”的自定义函数来索引我要删除的子字符串。我不太喜欢使用正则表达式,所以为了简单起见,我将此函数限制为固定匹配

strpos_fixed=function(x,y){
  a<-regexpr(y, x,fixed=T)
  b<-a[1]
  return(b)
}


rm_substr<-function(string,rm_start,rm_end){

  sub1<-substr(string,1,strpos_fixed(string, rm_start)-1)

  sub2<-substr(string, strpos_fixed(string,rm_end)+nchar(rm_end), 
               nchar(string))

  new <- gsub("\\s{2,}"," ",paste(sub1, sub2))

  return(new)
}

mystring <- "Hello, how are {you} doing?"
rm_substr(mystring, "{", "}")
strpos\u fixed=函数(x,y){

a
stringi::stri_sub(mystring,16,20)是的,这已经非常优雅了!谢谢。另一个选项是:
stringr::str_sub(mystring,16,20)
s <- "Hello, how are {you} doing?"
ix <- c(16, 20)
strpos_fixed=function(x,y){
  a<-regexpr(y, x,fixed=T)
  b<-a[1]
  return(b)
}


rm_substr<-function(string,rm_start,rm_end){

  sub1<-substr(string,1,strpos_fixed(string, rm_start)-1)

  sub2<-substr(string, strpos_fixed(string,rm_end)+nchar(rm_end), 
               nchar(string))

  new <- gsub("\\s{2,}"," ",paste(sub1, sub2))

  return(new)
}

mystring <- "Hello, how are {you} doing?"
rm_substr(mystring, "{", "}")