# Re: [R] counts of each column that are not NA, and/or greater than column means

From: Gabor Csardi <csardi_at_rmki.kfki.hu>
Date: Mon, 4 Feb 2008 09:32:33 +0100

On Mon, Feb 04, 2008 at 03:21:10PM +0800, Ng Stanley wrote:
> Hi,
>
> Given a test matrix, test <- matrix(c(1,2,3,NA,2,3,NA,NA,2), 3,3)
>
> A) How to compute the counts of each column (excluding the NA) i.e., 3, 2, 1

apply(test, 2, function(x) sum(!is.na(x)))

> B) How to compute the counts of each column (excluding the NA) that are
> greater than the column means ? i.e., 1, 1, 0

apply(test, 2, function(x) sum(x > mean(x, na.rm=TRUE), na.rm=TRUE))

In general, you need ?apply to calculate something for each row/column of a matrix.

Gabor

> I could write a for loop, but hope to use better alternative.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

```--
Csardi Gabor <csardi_at_rmki.kfki.hu>    UNIL DGM

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help