How do I remove part of a string? For example in ATGAS_1121
I want to remove everything before _
.
Use regular expressions. In this case, you can use gsub
:
gsub("^.*?_","_","ATGAS_1121") [1] "_1121"
This regular expression matches the beginning of the string (^), any character (.) repeated zero or more times (*), and underscore (_). The ? makes the match "lazy" so that it only matches are far as the first underscore. That match is replaced with just an underscore. See ?regex
for more details and references
You can use a built-in for this, strsplit:
> s = "TGAS_1121" > s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2] > s1 [1] "1121"
strsplit returns both pieces of the string parsed on the split parameter as a list. That's probably not what you want, so wrap the call in unlist, then index that array so that only the second of the two elements in the vector are returned.
Finally, the fixed parameter should be set to TRUE to indicate that the split parameter is not a regular expression, but a literal matching character.
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