2

How can I remove "/" from the end of my data. Let's assume this is my data

#input 
ID    page
 1    www.example.com/, ww.example.com/flight, www.example.com/flight/
 2    www.example.com/, ww.example.com/flight

I wish to remove "/" from those who had as their last character and my output will be like that

 #output 
 ID    page
 1    www.example.com, ww.example.com/flight, www.example.com/flight
 2    www.example.com, ww.example.com/flight
MFR
  • 2,049
  • 3
  • 29
  • 53

2 Answers2

7

One option:

gsub("/(?=,|$)", "", as.character(df$page), perl = TRUE)
#[1] "www.example.com, ww.example.com/flight, www.example.com/flight"
#[2] "www.example.com, ww.example.com/flight"

This checks if a / is followed by either a comma , or the end of the string $ and if that is found, the / is replaced by "", i.e. it is removed. Since this is a lookbehind, we use perl = TRUE.

Other option (less efficient):

sapply(strsplit(as.character(df$page), ", ", fixed = TRUE), function(x) toString(sub("/$", "", x)))
#[1] "www.example.com, ww.example.com/flight, www.example.com/flight"
#[2] "www.example.com, ww.example.com/flight" 
talat
  • 68,970
  • 21
  • 126
  • 157
2

We can use gsub without the lookarounds.. Here, we remove the / followed by either at the end of the string ($) or a , and replace it with ,. In the subsequent sub we remove the , at the end.

df1$page <- sub(",$", "", gsub("/($|,)", ",", df1$page))

df1$page
#[1] "www.example.com, ww.example.com/flight, www.example.com/flight" 
#[2] "www.example.com, ww.example.com/flight"         

Or another option is

 gsub("/(?!\\b)", "", df1$page, perl = TRUE)
 #[1] "www.example.com, ww.example.com/flight, www.example.com/flight" 
 #[2] "www.example.com, ww.example.com/flight"     
akrun
  • 874,273
  • 37
  • 540
  • 662