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
Using gsub() Function and \\ It is also possible to remove all characters in front of a point using the gsub function.
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.
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.
You can use basename
:
paste(trimws(basename(x)),collapse=" ")
# [1] "my cat is handsome"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With