[R] length with missing values

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Oct 15 14:11:40 CEST 2004


On Fri, 15 Oct 2004, Sundar Dorai-Raj wrote:

> Luis Rideau Cruz wrote:
> 
> > I have a martix with missing values( in which I want the sample size by
> > column)
> > When I :
> > 
> > apply(matrix,2,length)
> > 
> > I get the length of the vector regardless of missing values.
> > I can't pass an argument to length in apply.
> > 
> > Alternatively I could 
> > 
> > ifelse ( is.na ( matrix [, "columns in matrix " ] ) , 0 , 1)
> > 
> > Is there any easier way?
> > 
> 
> I think you almost have it:
> 
> colSums(ifelse(is.na(x), 0, 1))
> 
> will return the number of non-NA elements in each column of x.

colSums(!is.na(x)) is the same, and more obvious, I think.
Remember logical values are coerced to 0/1 in an arithmetical context.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list