Reputation: 45
I would like to remove the last "/" (special character) from a data-frame column.
For example there are 2 entries
1. "/mobile_phones" and
2. "/mobile_phones/".
The text can have multiple '/' in middle for example:
"/accessories-bandanas_and_headbands/womens/"
.
I would just like to remove rightmost '/' .
I tried the following gsub query
ga.data$landingPagePath <- gsub('^\\/&', '', ga.data$landingPagePath)
Upvotes: 3
Views: 75
Reputation: 76683
That's a simple regex. Note that you don't need to escape the '/', it's not a special character.
x <- c("/mobile_phones", "/mobile_phones/", "/accessories-bandanas_and_headbands/womens/")
sub("/\\s*$", "", x)
#[1] "/mobile_phones"
#[2] "/mobile_phones"
#[3] "/accessories-bandanas_and_headbands/womens"
Note also that since it is only one character to be removed, sub
will do the job, gsub
should be reserved for when there are multiple occurences of the pattern.
Upvotes: 4
Reputation: 79378
Since you are only interested in the last /
then you would invoke the $
which indicates that the string ends after the symbol /
. Also you don't need to use gsub
. You can use sub
since you are only replacing one thing in every line
vec=c("/mobile_phones",
"/mobile_phones/",
"/accessories-bandanas_and_headbands/womens/")
sub("/$","",vec)
[1] "/mobile_phones" "/mobile_phones"
[3] "/accessories-bandanas_and_headbands/womens"
Upvotes: 3