[R] String position character replacement

Yang, Joy (NIH/NHGRI) [F] joy.yang at nih.gov
Wed Feb 8 22:03:29 CET 2012


Oh cool! I didn't realize you could assign a different value to a substring like that.

Thanks!
Joy
________________________________________
From: Petr Savicky [savicky at cs.cas.cz]
Sent: Wednesday, February 08, 2012 3:26 PM
To: r-help at r-project.org
Subject: Re: [R] String position character replacement

On Wed, Feb 08, 2012 at 01:30:55PM -0500, Sarah Goslee wrote:
> And here's an alternative solution:
>
> subchar <- function(string, pos, char="-") {
>       for(i in pos) {
>       string <- gsub(paste("^(.{", i-1, "}).", sep=""), "\\1-", string)
>       }
>       string
> }

Hi.

Try the following modification.

  subchar2 <- function(string, pos) {
    for(i in pos) {
        substr(string, i, i) <- "-"
    }
    string
  }

  avec <- c("hellohowareyoudoing", "imgoodhowareyou", "goodandyou", "yesimgoodijusttoldyou", "ohyesthatsright")
  alist <- list(c(3, 9), c(3, 4), c(4, 7), c(5,6,7,8,9), c(2,5,7,12))
  sapply(1:length(avec), function(x) subchar2(avec[x], alist[[x]]))

  [1] "he-lohow-reyoudoing"   "im--odhowareyou"       "goo-an-you"
  [4] "yesi-----ijusttoldyou" "o-ye-t-atsr-ght"

Hope this helps.

Petr Savicky.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list