Hi Joy,

Perhaps not the easiest way, but the following seems to work:

x <- c("hellohowareyoudoing", "imgoodhowareyou", "goodandyou",
"yesimgoodijusttoldyou", "ohyesthatsright")
pos <- list(c(3, 9), c(3,4), c(4,7), 5:9, c(2, 5, 7, 12))

sapply(1:length(pos), function(i){
    xx <- strsplit(x, "")[[i]]
    xx[pos[[i]]] <- "-"
    paste(xx, sep = "", collapse = "")
})

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



On Wed, Feb 8, 2012 at 12:33 PM, Yang, Joy (NIH/NHGRI) [F] <> wrote:

> Hi,
>
> Is there a way to efficiently replace specified indices in a string with
> another character? For example, if I had a vector of strings such as
>
> [1] "hellohowareyoudoing"
> [2] "imgoodhowareyou"
> [3] "goodandyou"
> [4] "yesimgoodijusttoldyou"
> [5] "ohyesthatsright"
>
> and had a list of positions that I want to replace with the character "-"
>
> [[1]]
> [1]  3  9
>
> [[2]]
> [1]  3  4
>
> [[3]]
> [1]  4  7
>
> [[4]]
> [1] 5 6 7 8 9
>
> [[5]]
> [1]  2  5  7 12
>
> I would like to get
>
> [1] "he-lohow-reyoudoing"
> [2] "im--odhowareyou"
> [3] "goo-an-you"
> [4] "yesi-----ijusttoldyou"
> [5] "o-ye-t-atsr-ght"
>
> Is there an easy way to do this? Or would the easiest way be writing a
> function to take substrings of the original vector and pasting in the
> replacement character?
>
> Thanks in advance!
> Joy
> ______________________________________________
> [email protected] 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.
>

        [[alternative HTML version deleted]]

______________________________________________
[email protected] 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.

Reply via email to