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
}
}
If it is binary,
sum(!!myarray)
#[1] 3
Or
sum(myarray) #based on comments from @thelatemail
If not binary,
sum(myarray==1)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With