MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Counting Categories

  • To: mathgroup at smc.vnet.net
  • Subject: [mg96871] Re: [mg96798] Counting Categories
  • From: Darren Glosemeyer <darreng at wolfram.com>
  • Date: Thu, 26 Feb 2009 07:58:30 -0500 (EST)
  • References: <200902250903.EAA15666@smc.vnet.net> <49A568BC.4040207@wolfram.com> <8384DD65-183D-41F4-AEA5-D48DF76BA0A8@videotron.ca>

Gregory Lypny wrote:
> Thank you, Darren.  I guess my only other question would be how to 
> sort either the original data or the output so that it has the same 
> ordering as the choices {red, blue, green}, {small, medium, big}.
>
> Regards,
>
>     Gregory
>
> On Wed, Feb 25, 2009, at 10:50 AM, Darren Glosemeyer wrote:
>
>> You mentioned Cases, but I think you meant Count. Tally will do the 
>> counting you described.
>>
>> In[1]:= data = Transpose[{RandomChoice[{red, blue, green}, 20],
>>          RandomChoice[{small, medium, big}, 20]}];
>>
>> In[2]:= Tally[data]
>>
>> Out[2]= {{{blue, medium}, 6}, {{green, medium}, 2}, {{red, medium}, 
>> 2}, {{green, small}, 5},
>> >    {{blue, small}, 1}, {{red, small}, 2}, {{red, big}, 2}}
>>
>>
>> Darren Glosemeyer
>> Wolfram Research

One possibility is to replace the colors and sizes by indexes, tally the 
indexed data, sort the tallied results, and then replace the indexes by 
the original values.

In[1]:= data = Transpose[{RandomChoice[{red, blue, green}, 20],
            RandomChoice[{small, medium, big}, 20]}];

(* store values in a new variable and replace first elements by color 
indexes and second elements by size indexes *)

In[2]:= orderdata = data;

In[3]:= orderdata[[All, 1]] =
          orderdata[[All, 1]] /. Thread[Rule[{red, blue, green}, {1, 2, 
3}]];

In[4]:= orderdata[[All, 2]] =
          orderdata[[All, 2]] /.
           Thread[Rule[{small, medium, big}, {1, 2, 3}]];

(*Tally and Sort to get the tallies in the desired order*)

In[5]:= tallies = Sort[Tally[orderdata]];

(* undo the indexing *)

In[6]:= tallies[[All, 1, 1]] =
          tallies[[All, 1, 1]] /. Thread[Rule[{1, 2, 3}, {red, blue, 
green}]];

In[7]:= tallies[[All, 1, 2]] =
          tallies[[All, 1, 2]] /.
           Thread[Rule[{1, 2, 3}, {small, medium, big}]];

In[8]:= tallies

Out[8]= {{{red, small}, 2}, {{red, medium}, 2}, {{red, big}, 2}, {{blue, 
small}, 2}, {{blue, big}, 1},
 
 >    {{green, small}, 4}, {{green, medium}, 3}, {{green, big}, 4}}

(* compare with Tally[]ing the original data to see that counts agree, 
though the order is different *)

In[9]:= Tally[data]

Out[9]= {{{green, big}, 4}, {{green, medium}, 3}, {{red, medium}, 2}, 
{{red, big}, 2},
 
 >    {{blue, small}, 2}, {{blue, big}, 1}, {{green, small}, 4}, {{red, 
small}, 2}}


Darren Glosemeyer
Wolfram Research


  • Prev by Date: Re: Manipulating list of functions
  • Next by Date: Re: Re: Manipulating list of functions
  • Previous by thread: Re: Counting Categories
  • Next by thread: Re: Counting Categories