Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how to remove everything before the last slash

Tags:

string

regex

r

gsub

I have a dataset say

x <- c('test/test/my', 'et/tom/cat', 'set/eat/is', 'sk / handsome')

I'd like to remove everything before (including) the last slash, the result should look like

my cat is handsome

I googled this code which gives me everything before the last slash

gsub('(.*)/\\w+', '\\1', x)
[1] "test/test" "et/tom"    "set/eat"   "sk / tie"

How can I change this code, so that the other part of the string after the last slash can be shown?

Thanks

like image 895
angel0smile Avatar asked Mar 26 '18 20:03

angel0smile


People also ask

How do I delete everything before a character in R?

Using gsub() Function and \\ It is also possible to remove all characters in front of a point using the gsub function.

How do I remove part of a string in R?

Remove Specific Character from StringUse gsub() function to remove a character from a string or text in R. This is an R base function that takes 3 arguments, first, the character to look for, second, the value to replace with, in our case we use blank string, and the third input string were to replace.

How do I remove part of a variable in R?

To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.


2 Answers

You can use basename:

paste(trimws(basename(x)),collapse=" ")
# [1] "my cat is handsome"
like image 70
Moody_Mudskipper Avatar answered Oct 24 '22 18:10

Moody_Mudskipper


Using strsplit

> sapply(strsplit(x, "/\\s*"), tail, 1)
   [1] "my"       "cat"      "is"       "handsome"

Another way for gsub

> gsub("(.*/\\s*(.*$))", "\\2", x) # without 'unwanted' spaces
[1] "my"       "cat"      "is"       "handsome"

Using str_extract from stringr package

> library(stringr)
> str_extract(x, "\\w+$") # without 'unwanted' spaces
[1] "my"       "cat"      "is"       "handsome"
like image 21
Jilber Urbina Avatar answered Oct 24 '22 17:10

Jilber Urbina