[R] subset by multiple columns satisfying the same condition

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sun Mar 18 20:38:24 CET 2007


Frank Duan wrote:
> Hi All,
>
> I have a very simple question. Suppose I had a data frame with 100 columns,
> now I wanted to select rows with the values of  some columns satisfying the
> same condition, like all equal to "Tom". I know I can use the 'and' operator
> "&", but it's painful if there were many columns.
>
> Can anyone give me some advice? Thanks in advance,
>   
Here's one way:
 
rowSums(myframe != "Tom") == 0

The following approach might generalize more easily, though

 do.call("pmin", lapply(myframe, "==", "Tom"))

(notice that pmin on logical vectors is TRUE, if all are TRUE, else 
FALSE or NA).



More information about the R-help mailing list