0
$\begingroup$

I have a data set like the following, and the first column contains the groupings. However, some are labelled slightly differently. I need to remove all characters following the punctuation used (bracket, semicolon, comma).

groups <- c("Group1", "Group1", "Group1;Group1", "Group1(subset)", "Group1,ex" )

I would like this to present all of these just as Group1 (so they would all appear the same as the first two) - so to remove all characters in the string following the punctuation. I then need to repeat this for 1000s of groups, all in that same column of my dataset).

I know gsub is an option, but I'm not clear on how to use it to remove all of a string following a number of different characters, or on how to use it on just one column of a very large dataset.

$\endgroup$
1
  • 2
    $\begingroup$ gsub("[,;(].*$","",groups) $\endgroup$
    – Valentas
    May 2, 2020 at 13:40

2 Answers 2

0
$\begingroup$
substr(groups,1,6)
'Group1''Group1''Group1''Group1''Group1'
$\endgroup$
0
$\begingroup$

You mention this will be needed for 1000s of groups with potentially lots of different separator-characters after the number. Here's an option that should be able to extract the first instance of the name regardless of the group number or the separator that follows it:

sub("^(Group\\d+).*", "\\1", groups)

The main innovations being that it uses the ^ to anchor the match at the start of the string, and the \\d+ to match any number of digits after the word "Group". The "\\1" instructs sub to use the first capture group (in this case the region surrounded by ()) as the replacement. You could also do the same thing in the stringr package:

stringr::str_extract(groups, "^Group\\d+")

which I just prefer the syntax of, in extraction cases!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.