Extract/Remove portion of an Integer or string with random digits/characters in R

StackOverflow https://stackoverflow.com/questions/22256457

  •  11-06-2023
  •  | 
  •  

Question

Say I have an integer

x <- as.integer(442009)

or a character string

y <- "a10ba3m1"

How do I eliminate the last two digits/character of integer/string of any length in general ?

Was it helpful?

Solution

substr returns substrings:

substr(x, 1, nchar(x)-2)
# [1] "4420"
substr(y, 1, nchar(y)-2)
# [1] "a10ba3"

OTHER TIPS

If you know that the value is an integer, then you can just divide by 100 and convert back to integer (drop the decimal part). This is probably a little more efficient than converting it to a string then back.

> x <- as.integer(442009)
> floor(x/100)
[1] 4420

If you just want to remove the last 2 characters of a string then substr works.

Or, here is a regular expression that does it as well (less efficiently than substr:

> y <- "a10ba3m1"
> sub("..$", "", y)
[1] "a10ba3"

If you want to remove the last 2 digits (not any character) from a string and the last 2 digits are not guaranteed to be in the last 2 positions, then here is a regular expression that works:

> sub("[0-9]?([^0-9]*)[0-9]([^0-9]*)$", "\\1\\2", y)
[1] "a10bam"

If you want to remove up to 2 digits that appear at the very end (but not if any non digits come after them) then use this regular expression:

> sub("[0-9]{1,2}$", "", y)
[1] "a10ba3m"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top