Re: [R] count data with some conditions

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Sat, 01 Nov 2008 08:53:30 -0400

On Nov 1, 2008, at 3:30 AM, (Ted Harding) wrote:

> On 01-Nov-08 02:51:37, David Winsemius wrote:
>> Do you want the count of remaining elements which are strictly
>> greater than the first element?
>>
>>> length(which(a[1] < a[2:10]))
>> [1] 4
>>
>> or perhaps a bit more deviously:
>>
>>> sum( a[1]<a[2:10]+0 ) #adding 0 to TRUE or FALSE creates 1 or 0.
>> [1] 4
>
> No need to be devious! Simply
> sum(a[1] < a[2:10])
> # [1] 4
> will do it. The reason is that when TRUE or FALSE are involved in
> an arithmetic operation (which sum() is), they are cast into 1 or 0.

Agreed. I now also see that TRUE+TRUE and T+T both return 2. The second observation should be further warning to us newbies not to create variables named "T".

It's now been pointed out to me both on and off list that the +0 is unnecessary. I don't remember when I learned this, but it could not have been more than a year ago. I seem to remember that Gabor Grothendeick used the +0 device to convert a logical vector to a numeric vector. Perhaps it was for the purpose of making a matrix or something less necessarily arithmetical than sum() or "+".

-- 
David Winsemius, MD
Heritage Labs

>
>
> Ted.
>
>> On Oct 31, 2008, at 7:56 PM, sandsky wrote:
>>> Hi there,
>>> I have a data set:
>>>
>>> a=cbind(5,2,4,7,8,3,4,11,1,20)
>>>
>>> I want to count # of data, satistfying a[1]<a[2:10].
>>> Anyone helps me solving this case?
>>>
>>> Thank you in advance,
>>> Jin
>
> --------------------------------------------------------------------
> E-Mail: (Ted Harding) <Ted.Harding_at_manchester.ac.uk>
> Fax-to-email: +44 (0)870 094 0861
> Date: 01-Nov-08 Time: 07:30:17
> ------------------------------ XFMail ------------------------------
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
______________________________________________ R-help_at_r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Received on Sat 01 Nov 2008 - 12:58:58 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 01 Nov 2008 - 13:30:20 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive