[R] Count based on 2 conditions [Beginner Question]

Peter Ehlers ehlers at ucalgary.ca
Sun Sep 16 23:36:26 CEST 2012


On 2012-09-16 05:04, Rui Barradas wrote:
> Hello,
>
> Since logical values F/T are coded as integers 0/1, you can use this:
>
>
> set.seed(5712)  # make it reproducible
> n <- 1e3
> x <- data.frame(A = sample(0:1, n, TRUE), B = sample(0:10, n, TRUE))
>
> count <- sum(x$A == 1 & x$B > 5)  # 207


Another way:

   count <- sum(with(x, A*B > 5))

Peter Ehlers

>
> Hope this helps,
>
> Rui Barradas
>
> Em 16-09-2012 11:41, SirRon escreveu:
>> Hello,
>> I'm working with a dataset that has 2 columns and 1000 entries. Column 1 has
>> either value 0 or 1, column 2 has values between 0 and 10. I would like to
>> count how often Column 1 has the value 1, while Column 2 has a value greater
>> 5.
>>
>> This is my attempt, which works but doesn't seem to be very efficient,
>> especially when testing different values or columns.
>>
>> count=0
>> for (i in 1:1000) { if(dataset[i,2]>5 && ind[i,1]==1) { count=count+1}}
>>
>> I'm looking for a more efficient/elegant way to do this!
>>
>> Thanks!
>>
>>
>>
>> --
>> View this message in context: http://r.789695.n4.nabble.com/Count-based-on-2-conditions-Beginner-Question-tp4643282.html
>> Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list