开发者

R: How can I replace let's say the 5th element within a string?

开发者 https://www.devze.com 2023-03-22 15:11 出处:网络
I would like to convert the a string like be33szfuhm100060 into BESZFUHM0060. In order to replace the small letters with capital letters I\'ve so far used the gsub function.

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

In order to replace the small letters with capital letters I've so far used the gsub function.

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

Is there a way to tell this function to replace the 3rd and 4th string element? If not, I would really appreciate if you could tell me another way to solve this problem. Maybe there is also a more general solution to change a string element at a certain position into a capital 开发者_StackOverflow社区letter whatever the element is?


A couple of observations:

Cnverting a string to uppercase can be done with toupper, e.g.:

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

You could use substr to extract a substring by character positions and paste to concatenate strings:

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


As an alternative, if you are going to be doing this alot:

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


You can use substring to remove the third and fourth elements.

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


If you know what portions of the string you want based on their position(s), use substr or substring. As I mentioned in my comment, you can use toupper to coerce characters to uppercase.

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

精彩评论

暂无评论...
验证码 换一张
取 消