[R] Length of vector without NA's

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Thu Sep 23 18:01:54 CEST 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Joshua Wiley
> Sent: Thursday, September 23, 2010 8:23 AM
> To: Ralf B
> Cc: r-help Mailing List
> Subject: Re: [R] Length of vector without NA's
> 
> Hi Ralf,
> 
> The usual way (as others have shown you), takes advantage of the fact
> that the logical values TRUE and FALSE are counted as 1 and 0,
> respectively.  is.na() returns TRUE if the value is NA, so to find how
> many are not NA, the result is reversed using ' ! '.  Similar logic
> can be used to find how many meet any logical condition (e.g.,
> sum(1:10 < 5)   ).
> 
> Cheers,
> 
> Josh
> 
> On Thu, Sep 23, 2010 at 8:08 AM, Ralf B <ralf.bierig at gmail.com> wrote:
> > Hi,
> >
> > this following code:
> >
> > x<-c(1,2,NA)
> > length(x)
> >
> > returns 3, correctly counting numbers as well as NA's. How can I
> > exclude NA's from this count?
> >
> > Ralf
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
> 

Ralf,

While I might use the sum() function as others have posted, if you want the code to clearly show your intent (i.e. to get the length of a vector) then another option is

length(x[!is.na(x)])


Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204




More information about the R-help mailing list