Skip to content

remove columns containing all zeros (or other value)

6 messages · Anthony Dick, Jorge Ivan Velez, Gustavo Carvalho +2 more

#
Hello-

I would like to remove the columns of a matrix that contain all zeros. 
For example, from
 x<-matrix(c(1,5,3,2,1,4,0,0,0), ncol=3,nrow=3)

I would like to remove the third column. However, because this is in a 
loop I need a way to first determine which columns are all zeros, and 
only then remove them. I.e., I don't know which column of x contains all 
zeros until after x is created.

Thanks!

Anthony
#
You can also try this:

x[,-(which(colSums(x) == 0))]

Cheers,

Gustavo.
On Wed, Jan 14, 2009 at 8:01 PM, Anthony Dick <adick at uchicago.edu> wrote:
#
Sorry for the double post, but this is probably faster:

x[, colSums(x) != 0]

On Wed, Jan 14, 2009 at 8:22 PM, Gustavo Carvalho
<gustavo.bio+R at gmail.com> wrote:
#
Careful:

x <- matrix(c(1, 5, 3, 2, 1, 4, -1, 0, 1),
            ncol = 3, nrow = 3)
[,1] [,2] [,3]
[1,]    1    2   -1
[2,]    5    1    0
[3,]    3    4    1
[,1] [,2]
[1,]    1    2
[2,]    5    1
[3,]    3    4


Not quite the result wanted...  :-)

Try this:
[,1] [,2]
[1,]    1    2
[2,]    5    1
[3,]    3    4


x <- matrix(c(1, 5, 3, 2, 1, 4, -1, 0, 1),
              ncol = 3, nrow = 3)
[,1] [,2] [,3]
[1,]    1    2   -1
[2,]    5    1    0
[3,]    3    4    1



HTH,

Marc Schwartz
on 01/14/2009 04:29 PM Gustavo Carvalho wrote:
#
or this

x[,!(colSums(abs(x)) == 0)]
On Jan 15, 10:00?am, Marc Schwartz <wdwgol... at gmail.com> wrote: