[R] Delete Columns with zeros

Gavin Simpson
2008-01-31T16:19:40Z

hits=-2.6 tests?YES_00
X-USF-Spam-Flag: NO

On Thu, 2008-01-31 at 15:33 +0100, Jens Oldeland wrote:
> Hi,
>
> I know there have been some discussions on that topic. all their
> solutions failed in my case...
> My problem is that I have a dataframe with many zeros. but while
> plotting they are not useful.
> so I want to get rid of column 1,3,4,......,n i have 628 columns 1000
> rows, so I can??t look manually for the "empty" columns.
>
> Any possible Ideas?
>
>  > A250[1:5,1:4]
>
> AAPU ACTO ACRA ADBA
> A1100 0 0.0 0 0
> A20100 0 0.1 0 0
> A20200 0 0.0 0 0
> A400 0 1.0 0 0
> A4100 0 0.0 0 0
>
> I also didn??t find anything useful in "An Introduction to R".

You can use colSums() to get the column sums and then evaluate which are
greater than 0, and keep only those.

## example data
> dat <- data.frame(x = rep(0, 10), y = runif(10), z = rep(0, 10), a =
rnorm(10))
> dat
   x          y z           a
1  0 0.49300402 0 -0.04405118
2  0 0.59786017 0 -2.06150000
3  0 0.08937639 0 -0.48804730
4  0 0.81220978 0  0.89746064
5  0 0.08846686 0  1.89563799
6  0 0.11141525 0 -0.16550292
7  0 0.25976990 0  1.02780712
8  0 0.55836579 0 -1.19074561
9  0 0.19798582 0  0.29130921
10 0 0.65826305 0  1.29665594
> colSums(dat)
       x        y        z        a
0.000000 3.866717 0.000000 1.459024
> colSums(dat) > 0
    x     y     z     a
FALSE  TRUE FALSE  TRUE
> dat[, colSums(dat) > 0]
            y           a
1  0.49300402 -0.04405118
2  0.59786017 -2.06150000
3  0.08937639 -0.48804730
4  0.81220978  0.89746064
5  0.08846686  1.89563799
6  0.11141525 -0.16550292
7  0.25976990  1.02780712
8  0.55836579 -1.19074561
9  0.19798582  0.29130921
10 0.65826305  1.29665594

HTH

G

>
> thank you
>
> Jens
>
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%