RDocumentation: str_sub
  • AI Chat
  • Code
  • Report
  • Beta
    Spinner
    if(!require('stringr')) {
        install.packages('stringr')
        library('stringr')
    }
    hw <- "Hadley Wickham"
    
    # Negative indices
    str_sub(hw, -1)
    str_sub(hw, -7)
    str_sub(hw, end = -7)
    
    # Replacement form
    x <- "BBCDEF"
    str_sub(x, 1, 1) <- "A"; x
    str_sub(x, -1, -1) <- "K"; x
    str_sub(x, -2, -2) <- "GHIJ"; x
    str_sub(x, 2, -2) <- ""; x
    
    # If you want to keep the original if some argument is NA,
    # use omit_na = TRUE
    x1 <- x2 <- x3 <- x4 <- "AAA"
    str_sub(x1, 1, NA) <- "B"
    str_sub(x2, 1, 2) <- NA
    str_sub(x3, 1, NA, omit_na = TRUE) <- "B"
    str_sub(x4, 1, 2, omit_na = TRUE) <- NA
    x1; x2; x3; x4