[R] String position character replacement
Petr Savicky
savicky at cs.cas.cz
Wed Feb 8 21:26:42 CET 2012
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.
More information about the R-help
mailing list