R:我怎样才能代替字符串中的第5个元素?

Mik*_*ike 5 string replace r

我想把像be33szfuhm100060这样的字符串转换成BESZFUHM0060.

为了用大写字母替换小写字母,我到目前为止使用了gsub函数.

test1=gsub("be","BE",test)
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉这个函数替换第3和第4个字符串元素?如果没有,如果你能告诉我另一种解决这个问题的方法,我真的很感激.也许还有一个更通用的解决方案,将某个位置的字符串元素更改为大写字母,无论该元素是什么?

NPE*_*NPE 9

几点意见:

将字符串转换为大写可以使用toupper,例如:

> toupper('be33szfuhm100060')
> [1] "BE33SZFUHM100060"
Run Code Online (Sandbox Code Playgroud)

您可以使用substr按字符位置提取子字符串并paste连接字符串:

> x <- 'be33szfuhm100060'
> paste(substr(x, 1, 2), substr(x, 5, nchar(x)), sep='')
[1] "beszfuhm100060"
Run Code Online (Sandbox Code Playgroud)


jve*_*ani 7

作为替代方案,如果你要做这个很多:

String <- function(x="") {
  x <- as.character(paste(x, collapse=""))
  class(x) <- c("String","character")
  return(x)
}

"[.String" <- function(x,i,j,...,drop=TRUE) {
  unlist(strsplit(x,""))[i]
}
"[<-.String" <- function(x,i,j,...,value) {
  tmp <- x[]
  tmp[i] <- String(value)
  x <- String(tmp)
  x
}
print.String <- function(x, ...) cat(x, "\n")
## try it out
> x <- String("be33szfuhm100060")
> x[3:4] <- character(0)
> x
beszfuhm100060
Run Code Online (Sandbox Code Playgroud)