Gsub a every element after a keyword in R
Clash Royale CLAN TAG#URR8PPP
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.
gsub('string', '', list)
gsub('^string', '', list)
Thank you.
3 Answers
3
Following simple sub
may help you here.
sub
sub("\.string.*","",variable)
Explanation: Method of using sub
sub
sub(regex_to_replace_text_in_variable,new_value,variable)
Difference between sub
and gsub
:
sub
gsub
sub
: is being used for performing substitution on variables.
sub
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.
gsub
gsub
sub
From help page of R
:
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)
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'
You can use strsplit
. Here you split your string after a key word, and retain the first part of the string.
strsplit
x <- "this.is.an.example.string.that.I.have"
strsplit(x, '(?<=example)', perl=T)[[1]][1]
[1] "this.is.an.example"
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.