[R] help with gsub and grep functions

John Fox jfox at mcmaster.ca
Mon Oct 13 17:26:25 CEST 2003


Dear Oliver,

I believe that the following will give you what you want:

At 04:30 PM 10/13/2003 +0200, Martin Olivier wrote:
>Hi all,
>
>Let Names a vector of chatacters. For example,
>
> > Names
>[1] "g 604 be-0 -p1 (602 matches)" "g 606 Phli-0 -p2 (517 matches)"
>[3] "g 608 alu-0  (659 matches)"
>
>I try to use gsub or grep functions for two problems :
>
>1. First, I would like to delete all the characters between parentheses.
>[1] "g 604 be-0 -p1" "g 606 be-0 -p2"
>[3] "g 608 be-0 -p3"

gsub(" *$", "", gsub("\\(.*\\)$", "", Names))  # also deletes trailing blanks


>2. And, I would like to extract the characters between parentheses
>[1] "602 matches" "517 matches"
>[3] "659 matches"
>

posn <- regexpr("\\(.*\\)$", Names)
substring(Names, first=posn+1, last=posn+attr(posn,"match.length")-2)


>Any idea?
>
>Best regards,
>Olivier

I hope that this helps,
  John

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox




More information about the R-help mailing list