[R] remove columns containing all zeros (or other value)
andrew
andrewjohnroyal at gmail.com
Thu Jan 15 00:29:32 CET 2009
or this
x[,!(colSums(abs(x)) == 0)]
On Jan 15, 10:00 am, Marc Schwartz <wdwgol... at gmail.com> wrote:
> Careful:
>
> x <- matrix(c(1, 5, 3, 2, 1, 4, -1, 0, 1),
> ncol = 3, nrow = 3)
>
> > x
>
> [,1] [,2] [,3]
> [1,] 1 2 -1
> [2,] 5 1 0
> [3,] 3 4 1
>
> > x[, colSums(x) != 0]
>
> [,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:
>
> > x[, colSums(x) != 0]
>
> > On Wed, Jan 14, 2009 at 8:22 PM, Gustavo Carvalho
> > <gustavo.bi... at gmail.com> wrote:
> >> You can also try this:
>
> >> x[,-(which(colSums(x) == 0))]
>
> >> Cheers,
>
> >> Gustavo.
>
> >> On Wed, Jan 14, 2009 at 8:01 PM, Anthony Dick <ad... at uchicago.edu> wrote:
> >>> 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
>
> ______________________________________________
> R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list