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:
x[, colSums(x == 0) != nrow(x)]
? ? ?[,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)
x[, colSums(x == 0) != nrow(x)]
? ? ?[,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:
Sorry for the double post, but this is probably faster:
On Wed, Jan 14, 2009 at 8:22 PM, Gustavo Carvalho
<gustavo.bi... at gmail.com> wrote:
x[,-(which(colSums(x) == 0))]
On Wed, Jan 14, 2009 at 8:01 PM, Anthony Dick <ad... at uchicago.edu> wrote:
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.