[R] how to find a row index in a matrix or a data frame ?

Luedde, Mirko mirko.luedde at sap.com
Thu Nov 25 12:04:25 CET 2010


Hi all, thank you for quick help. 

Any ideas on (better) efficiency 
(with other data types)?

Best, Mirko 

-----Ursprüngliche Nachricht-----
Von: henrik.bengtsson at gmail.com [mailto:henrik.bengtsson at gmail.com] Im Auftrag von Henrik Bengtsson
Gesendet: Donnerstag, 25. November 2010 11:25
An: Luedde, Mirko
Cc: r-help at r-project.org
Betreff: Re: [R] how to find a row index in a matrix or a data frame ?

rows <- which(apply(mapply(x, r, FUN="=="), MARGIN=1, FUN=all));

/H

On Thu, Nov 25, 2010 at 1:59 AM, Luedde, Mirko <mirko.luedde at sap.com> wrote:
> Dear all,
>
> this looks pretty much a standard problem, but I couldn't find a
> satisfying and understandable solution.
>
> (A) Given a data frame (or matrix), e.g.
>
>      x <- data.frame(A=c(1, 2, 2), B=c(4, 5, 5))
>
>    and a row of this data frame, e.g.
>
>      r <- c(2, 5)
>
>    I need to find one row index i (or all such indices) such that r
>    is at the i-th row in x, that is, the expression
>
>      all(x[i,]==as.list(r))
>
>    evaluates to TRUE.  I can not evaluate an expression like
>
>      x[x[,1]==2 & x[,2]==5,]
>
>    because I do not know in advance how many columns x will have.
>
>    Basically, thus, I'm looking for an equivalent of "vectorfind" in
>    Scilab.
>
> (B) Which would be the most appropriate data type for x, matrix or
>    data frame or another type?
>
> (C) What will be better, searching for rows or searching for columns?
>
> Thank you for your help!
>
> Best, Mirko
>
> ______________________________________________
> 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