I am struggling to remove the substring before the underscore in my string. I want to use * (wildcard) as the bit before the underscore can vary:
a <- c("foo_5", "bar_7") a <- gsub("*_", "", a, perl = TRUE)
The result should look like:
> a [1] 5 7
I also tried stuff like "^*" or "?" but did not really work.
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.
The gsub() function in R is used to replace the strings with input strings or values. Note that, you can also use the regular expression with gsub() function to deal with numbers.
You can either use R base function gsub() or use str_replace() from stringr package to remove characters from a string or text.
Use the substr() Function to Remove the Last Characters in R The substr() function in R extracts or replaces a substring from a string. We pass the given string and the starting and final position of the required substring to the function.
The following code works on your example :
gsub(".*_", "", a)
Alternatively, you can also try:
gsub("\\S+_", "", a)
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