Skip to content

Instantly share code, notes, and snippets.

@leeper
Created March 10, 2016 11:05
Show Gist options
  • Save leeper/e443f76c43740ef6b374 to your computer and use it in GitHub Desktop.
Save leeper/e443f76c43740ef6b374 to your computer and use it in GitHub Desktop.
Positional character substitution
charsub <- function(x, i, value) {
out <- lapply(strsplit(x, ""), function(z) {
z <- `[<-`(z, i, value)
z[is.na(z)] <- " "
paste0(z, collapse = "")
})
unlist(out)
}
# SINGLE STRING
(x1 <- "hello world.")
## [1] "hello world."
charsub(x1, nchar(x1), "!")
## [1] "hello world!"
charsub(x1, 5:6, "no")
## [1] "hellnonoworld."
# VECTORIZED
x2 <- c("apple", "banana", "orange", "pineapple", "kiwi")
## [1] "apple" "banana" "orange" "pineapple" "kiwi"
charsub(x2, c(1, 7), c("X", "Y"))
## [1] "Xpple Y" "XananaY" "XrangeY" "XineapYle" "Xiwi Y"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment