Created
          March 10, 2016 11:05 
        
      - 
      
- 
        Save leeper/e443f76c43740ef6b374 to your computer and use it in GitHub Desktop. 
    Positional character substitution
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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