Skip to content

Instantly share code, notes, and snippets.

@expersso
Created March 10, 2016 13:18
Show Gist options
  • Save expersso/b558bb462cc4f690db81 to your computer and use it in GitHub Desktop.
Save expersso/b558bb462cc4f690db81 to your computer and use it in GitHub Desktop.
Character substitution by position
x2 <- c("apple", "banana", "orange", "pineapple", "kiwi")
# Original function
charsub <- function(x, i, value) {
out <- lapply(strsplit(x, ""), function(z) {
z <- `[<-`(z, i, value)
z[is.na(z)] <- " "
paste0(z, collapse = "")
})
unlist(out)
}
# Rewrite with simpler assignment + vapply
charsub2 <- function(x, i, value) {
vapply(strsplit(x, ""), function(z) {
z[i] <- value
z[is.na(z)] <- " "
paste0(z, collapse = "")
}, vector("character", 1), USE.NAMES = FALSE)
}
# Rewrite with stringi
library(stringi)
charsub3 <- function(x, i, value) {
vapply(x, function(z) {
z <- stri_pad_right(z, max(i))
for(j in seq_along(i))
stri_sub(z, i[j], i[j]) <- value[j]
z
}, vector("character", length = 1), USE.NAMES = FALSE)
}
library(microbenchmark)
microbenchmark(charsub(x2, c(1, 7), c("X", "Y")),
charsub2(x2, c(1, 7), c("X", "Y")),
charsub3(x2, c(1, 7), c("X", "Y")))
# Unit: microseconds
# expr min lq mean median uq max neval
# charsub(x2, c(1, 7), c("X", "Y")) 36.086 37.4100 40.53261 38.4040 41.052 51.647 100
# charsub2(x2, c(1, 7), c("X", "Y")) 38.073 39.7280 43.68439 41.7140 43.701 90.712 100
# charsub3(x2, c(1, 7), c("X", "Y")) 82.767 86.0775 92.52336 87.7325 97.003 135.406 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment