Search code examples
rstringcharactersubstr

Using substr() to delete a character


I have a character "abc" and want to delete the "b". I want to target by position. I tried:

x <- "abc"
substr(x, 2,3) <- ""

x
#[1] "abc"

Why is it not possible to delete a character from a string like this? How would I do it in a similarly simple approach?


Solution

  • You said that you "want to target by position", if what you mean is that you want to extract the second character from your string regardless of its value, then you can simply do:

    x <- paste0(substr(x, 1, 1), substr(x, 3, nchar(x)))
    # "ac" if x <- "abc" initially and "acd" if x <- "abcd" initially
    

    You can replace a character with substr() but not remove it (since you need to shift the position of all following characters, etc.). To achieve this you could combine substr and gsub like this (e.g. if you are sure your string doesn't contain dashes):

    substr(x, 2, 3) <- '-'
    gsub('-', '', x)
    

    If what you want is to remove the "b" occurences then gsub() as explained in the answers above is a good option.