Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove pattern from string with gsub

Tags:

r

gsub

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.

like image 284
user969113 Avatar asked Aug 02 '12 11:08

user969113


People also ask

How do I remove GSUB from R?

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.

What does gsub () do in R?

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.

How do I remove a letter from a string in R?

You can either use R base function gsub() or use str_replace() from stringr package to remove characters from a string or text.

How do I remove part of a string in R?

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.


2 Answers

The following code works on your example :

gsub(".*_", "", a) 
like image 67
Pop Avatar answered Oct 14 '22 05:10

Pop


Alternatively, you can also try:

gsub("\\S+_", "", a) 
like image 43
Madhu Sareen Avatar answered Oct 14 '22 06:10

Madhu Sareen