Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

replace

r

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 letter whatever the element is?

like image 246
Mike Avatar asked Jul 25 '11 16:07

Mike


People also ask

How do I replace a word in a string in R?

The gsub() function in R is used to replace the strings with input strings or values.

How do I remove a character from a string in R?

Use gsub() function to remove a character from a string or text in R.

How do you trim a string in R?

strtrim() function in R Language is used to trim a string to a specified display width.


2 Answers

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"
like image 190
NPE Avatar answered Nov 15 '22 07:11

NPE


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
like image 37
jverzani Avatar answered Nov 15 '22 06:11

jverzani