Re: [R] indices of rows containing one or more elements >0

From: Henrik Bengtsson <hb_at_stat.berkeley.edu>
Date: Tue, 12 Feb 2008 19:30:05 -0800

X <- matrix(c(0,2,0,1,0,0,3,5), ncol=2)

Informative version:
isPositive <- (X > 0)
nbrOfPositives <- apply(isPositive, MARGIN=1, FUN=sum) hasPositives <- (nbrOfPositives >= 1)
positiveRows <- which(hasPositives)

Compact version:
positiveRows <- which(rowSums(X > 0) >= 1)

If you have an extremely large number of rows and only a few columns, you might for speed purposes want to use an algorithm that iterates over columns instead, but I leave that as an exercise.

/Henrik

On Feb 12, 2008 6:40 PM, Ng Stanley <stanleyngkl_at_gmail.com> wrote:
> Hi,
>
> Given test <- matrix(c(0,2,0,1,3,5), 3,2)
>
> > test[test>0]
> [1] 2 1 3 5
>
> These are values >0
>
> > which(test>0)
> [1] 2 4 5 6
>
> These are array indices of those values >0
>
> > which(apply(test>0, 1, all))
> [1] 2
>
> This gives the row whose elements are all >0
>
> I can't seem to get indices of rows containing one or more elements >0
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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. Received on Wed 13 Feb 2008 - 03:37:14 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 13 Feb 2008 - 05:30:13 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive