Remove part of a string
Solution 1
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
Solution 2
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.
Solution 3
If you're a Tidyverse kind of person, here's the stringr solution:
R> library(stringr)
R> strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
R> strings %>% str_replace(".*_", "_")
[1] "_1121" "_1432" "_1121"
# Or:
R> strings %>% str_replace("^[A-Z]*", "")
[1] "_1121" "_1432" "_1121"
Solution 4
Here's the strsplit
solution if s
is a vector:
> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"
Solution 5
Maybe the most intuitive solution is probably to use the stringr
function str_remove
which is even easier than str_replace
as it has only 1 argument instead of 2.
The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern)
.
See example:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
Related videos on Youtube
Lisann
Updated on July 08, 2022Comments
-
Lisann almost 2 years
How do I remove part of a string? For example in
ATGAS_1121
I want to remove everything before_
. -
Richie Cotton about 12 yearsPrevious regex would match to the last underscore in the case of, e.g.,
gsub("^.*_","_","ATGAS_1121_xxx")
. Now fixed. -
Vasile over 8 years@Joshua I find it really useful that you explained the role of the regular expressions.
-
stevenjoe over 8 yearsVery helpful, thanks! FYI to get the first part of the string (i.e. before the '_'), replace the [2] on the end with a [1].
-
naught101 over 7 yearsThis also works with a vector of strings as the last argument. R is awesome like that.
-
d3hero23 about 2 years@verbamour do you know how to modify this to keep the first 2 elements of the string
-
verbamour about 2 years@d3hero23 I believe @stevenjoe answered that above. Applying his solution gives you
s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[1]))