[R] Wildcard for indexing?

Duncan Murdoch murdoch.duncan at gmail.com
Tue Feb 14 16:19:43 CET 2012


On 14/02/2012 10:10 AM, Johannes Radinger wrote:
> Hi,
>
> -------- Original-Nachricht --------
> >  Datum: Tue, 14 Feb 2012 09:59:39 -0500
> >  Von: "R. Michael Weylandt"<michael.weylandt at gmail.com>
> >  An: Johannes Radinger<JRadinger at gmx.at>
> >  CC: R-help at r-project.org
> >  Betreff: Re: [R] Wildcard for indexing?
>
> >  I think the grep()-family (regular expressions) will be the easiest
> >  way to do this, though it sounds like you might prefer grepl() which
> >  returns a logical vector:
> >
> >  ^[AB] # Starts with either an A or a B
> >  ^A_ # Starting with A_
> >
> >  a<-  c("A_A","A_B","C_A","BB","A_Asd"
> >  grepl("^[AB]", a)
> >  grepl("^A_")
>
> Yes grepl() is what I am looking for.
> is there also something like an OR statement e.g. if I want to
> select for elements that start with "as" OR "df"?

grepl("^(as|df)", a)

should work.  See ?regexp for all the possibilities, rules about 
operator precedence, etc.  (Or just use grepl("^as", a) | grepl("^df", a).)

Duncan Murdoch

> /johannes
>
> >
> >  Michael
> >
> >  On Tue, Feb 14, 2012 at 9:54 AM, Johannes Radinger<JRadinger at gmx.at>
> >  wrote:
> >  >  Hi,
> >  >
> >  >  I'd like to know if it is possible to use wildcards * for indexing...
> >  >  E.g. I have a vector of strings. Now I'd like to select all elements
> >  >  which start with A_*? I'd also need to combine that with logical
> >  operators:
> >  >
> >  >  "Select all elements of a vector that start with A (A*) OR that start
> >  with B (B*)"
> >  >
> >  >  Probably that is quite easy. I looked into grep() which I think might
> >  perform such tasks, but probably there is a more straigth forward solution.
> >  >
> >  >  a<- c("A_A","A_B","C_A","BB","A_Asd")
> >  >  a[a=="A_A"| a=="A_B"] # here I'd like an index but with wildcard
> >  >
> >  >  /johannes
> >  >  --
> >  >
> >  >  ______________________________________________
> >  >  R-help at r-project.org mailing list
> >  >  https://stat.ethz.ch/mailman/listinfo/r-help
> >  >  PLEASE do read the posting guide
> >  http://www.R-project.org/posting-guide.html
> >  >  and provide commented, minimal, self-contained, reproducible code.
>
> --
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list