Reputation: 67
I have values where some have a period (.
) in the end, here 95.2. and 87.5.:
c("25.3", "95.4", "95.6", "95.2.", "87.5.")
How can I remove the trailing periods? Desired result:
c(25.3, 95.4, 95.6, 95.2, 87.5)
Upvotes: 3
Views: 8767
Reputation: 11
You may also remove the period at the end of your string using the following code. The gsub function is from base r so no additional package would need to be loaded for this to work.
DF$Name <- gsub("\\.$", "", DF$Name)
Upvotes: 1
Reputation: 21400
There are really many ways you can do this; one is via backreference:
sub("(.*?)\\.$", "\\1", string)
[1] "25.3" "95.4" "95.6" "95.2" "87.5"
Here, you put everything prior to the final .
into a capturing group and 'remember' just that in sub
's replacment argument.
Data:
string <- c("25.3", "95.4", "95.6", "95.2.", "87.5.")
Upvotes: 0
Reputation: 16842
As an alternative to @akrun's answer, you can use str_remove
from the stringr
package. sub
lets you replace one string with another; in order to remove a string, you replace it with a blank string (i.e. ""
). str_remove
provides a shortcut that automatically handles the fact that your replacement is a blank string.
The regex \\.$
removes a dot (after escaping with the double backslashes) at the end of the string.
x <- c("25.3", "95.4", "95.6", "95.2.", "87.5.")
as.numeric(stringr::str_remove(x, "\\.$"))
#> [1] 25.3 95.4 95.6 95.2 87.5
Upvotes: 4
Reputation: 887148
We can use sub
to match the dot (.
- is a metacharacter meaning any character - so we either escape (\\.
) or place it in a square bracket to evaluate as the dot character) at the end ($
) of the string and replace it with blanks, then convert it to numeric
as.numeric(sub("[.]$", "", dat$Col))
Upvotes: 11