[R] Wildcard for indexing?

Sarah Goslee sarah.goslee at gmail.com
Tue Feb 14 16:00:47 CET 2012


Hi,

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

Do you want elements that start with A or B, as you state above, or elements
that start with A_A or A_B as here?

Either way, this is a job for grepl(), and it is quite easy:

> a <- c("A_A","A_B","C_A","BB","A_Asd")
>
> grepl("^[AB]", a)
[1]  TRUE  TRUE FALSE  TRUE  TRUE
> grepl("^A_[AB]", a)
[1]  TRUE  TRUE FALSE FALSE  TRUE

Sarah


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list