Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplest way to count number of ones in an array in R

Tags:

r

Is there a function which I can use to count the number of ones in an array in R? I was looking for something which would save me the overhead of

count = 0;
myarray = c(1,1,0,1,0)  
for(i in 1:length(myarray))
{
 if(myarray[i] == 1)
 {
  count = count+1
 }
}
like image 516
IAMTubby Avatar asked Dec 05 '25 12:12

IAMTubby


2 Answers

If it is binary,

 sum(!!myarray) 
 #[1] 3

Or

 sum(myarray) #based on comments from @thelatemail

If not binary,

sum(myarray==1)
like image 130
akrun Avatar answered Dec 07 '25 06:12

akrun


There is also, of course, table or tabulate:

myarray = c(1,1,0,1,0)
table(myarray)
# myarray
# 0 1 
# 2 3 
tabulate(myarray)
# [1] 3

Also, I would prefer sum(as.logical(myarray)) to double-negation with !! as @akrun used in his answer.

like image 20
A5C1D2H2I1M1N2O1R2T1 Avatar answered Dec 07 '25 07:12

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!