Reputation: 1624
I have a column of a dataframe in R like this:
names <- data.frame(name=c("ABC", "ABC-D", "ABCD-"))
I would like to remove the hyphen at the end of the strings while maintaining the hyphen in the middle of them. I've tried a few expressions like:
names$name <- gsub("+-\\w", "", names$name)
# the desired output is "ABC", "ABC-D", and "ABCD", respectively
While several combinations remove the hyphens entirely, I'm not sure how to specify the string boundary and the hyphen together.
Thanks!
Upvotes: 1
Views: 3609
Reputation: 24074
Try :
gsub("\\-$", "", names$name)
# [1] "ABC" "ABC-D" "ABCD"
$
tells R
that the (escaped) hyphen is at the end of the word
Although, as the -
is placed first in the regex
you don't need to escape it so this works too:
gsub("-$", "", names$name)
#[1] "ABC" "ABC-D" "ABCD"
Upvotes: 2