Frank Duan
2007-Mar-18 18:36 UTC
[R] subset by multiple columns satisfying the same condition
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, FD [[alternative HTML version deleted]]
Peter McMahan
2007-Mar-18 18:56 UTC
[R] subset by multiple columns satisfying the same condition
say x is you rdata frame and y is the vector of column indices you want to match to a condition: x[apply(x[y]=="Tom",1,all),] still, i feel like there's probably a better way... On Mar 18, 2007, at 1:36 PM, 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, > > FD > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch 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.
Peter Dalgaard
2007-Mar-18 19:38 UTC
[R] subset by multiple columns satisfying the same condition
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).
Seemingly Similar Threads
- Deleting rows satisfying a certain condition (sum of some colums>2)
- How to compare X1 = X2 = ... = Xn?
- Generate a matrix Q satisfying t(Q)%*%Q=Z and XQ=W
- Suggestion: Adding quick rowMin and rowMax functions to base package
- How to calculate the stratified means in a data frame?