R: How can I replace let say the 5th element inside the string?

I would like to convert a string like be33szfuhm100060 to BESZFUHM0060.

To replace lowercase letters with uppercase letters, I still used the gsub function.

test1=gsub("be","BE",test)

Is there any way to tell this function to replace the third and fourth string elements? If not, I would really appreciate it if you could tell me another way to solve this problem. Perhaps there is also a more general solution for changing a line item in a certain position to a capital letter regardless of the item?

+5
source share
4 answers

A few observations:

toupper, :

> toupper('be33szfuhm100060')
> [1] "BE33SZFUHM100060"

substr paste :

> x <- 'be33szfuhm100060'
> paste(substr(x, 1, 2), substr(x, 5, nchar(x)), sep='')
[1] "beszfuhm100060"
+9

, :

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
+7

substring .

x <- "be33szfuhm100060"
paste(substring(x, 1, 2), substring(x, 5), sep = "")
+2

, , substr substring. , toupper .

paste( toupper(substr(test,1, 2)),
       toupper(substr(test,5,10)),
       substr(test,12,nchar(test)),sep="")
# [1] "BESZFUHM00060"
0

All Articles