Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use R gsub function to remove punctuation and number?

I have a column contain and I wanted to remove the (*) at the end of the string but some has space in between and some has not:

Variable
0. No (1)
1. Yes(2)
2. Refuse to Answer (3)
3. Agree(4)
4. Disagree (5)

Desired outcome:

Variable
0.No
1.Yes
2.Refuse to Answer
3.Agree
4.Disagree 

I want to remove the punctuation marks (), but I left the dot and removed the number inside the blanket.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to do it one by one:

gsub("[[:punct:]]","",df$column)
gsub("[[:num:]]","",df$column)

but it will also remove the front part of the string. Is there any advice? thanks.

>Solution :

You can use sub with *\\(.* to match a space 0 to n times *, followed by ( \\( and followed by anything .*.
\\. * will match . followed by 0 to n space. Here also instead of \\. * would give the desired result.

sub("\\. *", ".", sub(" *\\(.*", "", s))
#[1] "Variable"           "0.No"               "1.Yes"             
#[4] "2.Refuse to Answer" "3.Agree"            "4.Disagree"        

Data

s <- c("Variable", "0. No (1)", "1. Yes(2)", "2. Refuse to Answer (3)",
  "3. Agree(4)", "4. Disagree (5)")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading