[R] counting the number of ones in a vector

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Thu Mar 4 20:09:23 CET 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
> Behalf Of sjaffe
> Sent: Thursday, March 04, 2010 10:59 AM
> To: r-help at r-project.org
> Subject: Re: [R] counting the number of ones in a vector
> 
> 
> I got tired of writing length(which()) so I define a useful function which I
> source in my .Rprofile:
> 
> count <- function( x ) length(which(x))
> 
> Then:
> 
> count( x == 1 )
> 

How about  sum(x==1) ?  No need to write a new function, and it is even 2 characters less to type.

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