Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gsub a every element after a keyword in R

I'd like to remove all elements of a string after a certain keyword. Example :

this.is.an.example.string.that.I.have

Desired Output :

This.is.an.example

I've tried using gsub('string', '', list) but that only removes the word string. I've also tried using the gsub('^string', '', list) but that also doesn't seem to work.

Thank you.

like image 245
eigenfoo Avatar asked Nov 24 '25 05:11

eigenfoo


2 Answers

Following simple sub may help you here.

sub("\\.string.*","",variable)

Explanation: Method of using sub

sub(regex_to_replace_text_in_variable,new_value,variable)

Difference between sub and gsub:

sub: is being used for performing substitution on variables.

gsub: gsub is being used for same substitution tasks only but only thing it will be perform substitution on ALL matches found though sub performs it only for first match found one.

From help page of R:

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

like image 104
RavinderSingh13 Avatar answered Nov 25 '25 19:11

RavinderSingh13


You can try this positive lookbehind regex

S <- 'this.is.an.example.string.that.I.have'
gsub('(?<=example).*', '', S, perl=TRUE)
# 'this.is.an.example'
like image 20
CPak Avatar answered Nov 25 '25 19:11

CPak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!