[R] remove columns containing all zeros (or other value)
Marc Schwartz
wdwgolfer at gmail.com
Thu Jan 15 00:00:26 CET 2009
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.bio+R 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 <adick 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
>>>
More information about the R-help
mailing list