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

后端 未结 3 1099
孤街浪徒
孤街浪徒 2021-01-02 07:43

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 R

相关标签:
3条回答
  • 2021-01-02 08:22

    The best way to do this is with a regular expression replacement statement. How you do this depends on the language that you are using.

    Here's the regex pattern you need to identify the trailing numbers

    (.\d{1,2})^

    And you should simply replace the matches with ""

    0 讨论(0)
  • 2021-01-02 08:25

    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.
    0 讨论(0)
  • 2021-01-02 08:46

    Try this

    gsub("\\.[[:digit:]]*$", "", z)
    
    0 讨论(0)
提交回复
热议问题