Hi, Can someone tell me how to remove rows of zeros from a matrix? For example if I have the following matrix, 0 0 0 1 2 8 0 0 4 56 I should end up with 0 1 2 8 4 56 -- Thanks, Jim. [[alternative HTML version deleted]]
Assuming the matrix is named X: X[which(rowSums(X) > 0),] should work. Also, this list is a text-only list. As you are using gmail, sending text only messages is very easy, and may clear confusion in future posts. HTH, Jon On Thu, Jun 2, 2011 at 11:23 AM, Jim Silverton <jim.silverton at gmail.com> wrote:> Hi, > Can someone tell me how to remove rows of zeros from a matrix? > For example if I have the following matrix, > > 0 0 > 0 1 > 2 8 > 0 0 > 4 56 > > I should end up with > 0 1 > 2 8 > 4 56 > > -- > Thanks, > Jim. > > ? ? ? ?[[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. >-- ==============================================Jon Daily Technician ==============================================#!/usr/bin/env outside # It's great, trust me.
On Thu, Jun 02, 2011 at 11:23:28AM -0400, Jim Silverton wrote:> Hi, > Can someone tell me how to remove rows of zeros from a matrix? > For example if I have the following matrix, > > 0 0 > 0 1 > 2 8 > 0 0 > 4 56 > > I should end up with > 0 1 > 2 8 > 4 56Hi. Try the following a <- matrix(c(0, 0, 2, 0, 4, 0, 1, 8, 0, 56), ncol=2) a[rowSums(a != 0) != 0, ] Hope this helps. Petr Savicky.
On Jun 2, 2011, at 11:35 AM, Petr Savicky wrote:> On Thu, Jun 02, 2011 at 11:23:28AM -0400, Jim Silverton wrote: >> Hi, >> Can someone tell me how to remove rows of zeros from a matrix? >> For example if I have the following matrix, >> >> 0 0 >> 0 1 >> 2 8 >> 0 0 >> 4 56 >> >> I should end up with >> 0 1 >> 2 8 >> 4 56 > > Hi. > > Try the following > > a <- matrix(c(0, 0, 2, 0, 4, 0, 1, 8, 0, 56), ncol=2) > a[rowSums(a != 0) != 0, ]To avoid removing rows where non-zero elements do sum to 0 one could use the only slightly longer test that first converts "a" to logical: a <- matrix(c(1, 0, 2, 0, 4, -1, 1, 8, 0, 56), ncol=2) a[ rowSums(a==0) != ncol(a), ] [,1] [,2] [1,] 1 -1 [2,] 0 1 [3,] 2 8 [4,] 4 56 -- David Winsemius, MD West Hartford, CT
Apparently Analagous Threads
- Match numeric vector against rows in a matrix?
- removing particular row from matrix
- generating random covariance matrices (with a uniform distribution of correlations)
- Removing duplicated rows within a matrix, with missing data as wildcards
- How to subset a matrix?