Counting Values in R Vector

Posted by GTyler on Stack Overflow See other posts from Stack Overflow or by GTyler
Published on 2012-11-07T22:34:56Z Indexed on 2012/11/07 23:00 UTC
Read the original article Hit count: 142

Filed under:
|

I have a large vector of percentages (0-100) and I am trying to count how many of them are in specific 20% buckets (<20, 20-40, 40-60,60-80,80-100). The vector has length 129605 and there are no NA values. Here's my code:

x<-c(0,0,0,0,0)
for(i in 1: length(mail_return))
{
    if (mail_return[i]<=20)
    {
        x[1] = x[1] + 1
    }
    if (mail_return[i]>20 && mail_return[i]<=40)
    {
        x[2] = x[2] + 1
    }
    if (mail_return[i]>40 && mail_return[i]<=60)
    {
        x[3] = x[3] + 1
    }
    if (mail_return[i]>60 && mail_return[i]<=80)
    {
        x[4] = x[4] + 1
    }
    else
    {   
        x[5] = x[5] + 1
    }
}

But sum(x) is giving me length 133171. Shouldn't it be the length of the vector, 129605? What's wrong?

© Stack Overflow or respective owner

Related posts about r

    Related posts about vector