Braden Braden - 1 year ago 63
R Question

Delete a dot and a number at the end of a character string

How do I delete a number (one or two digits in length) and the dot directly preceding it each time it occurs at the end of a string within a specific variable in

? Example:

z<-c("awe", "", "ted.5", "you.88.tom")

I only want to remove the
and the

Answer Source

You just need a simple regular expression:

z_new = gsub("\\.[0-9]*$", "", z)

A few comments:

  1. The first argument in gsub is the pattern we are looking for. The second argument is what to replace it with (in this case, nothing).
  2. The $ character looks for the pattern at the end of the string
  3. [0-9]* looks for 1 or more digits. Alternatively, you could use \\d* or [[:digit:]]*.
  4. \\. matches the full stop. We need to escape the full stop with two slashes.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download