2
$\begingroup$

Is it possible to implement BinCounts for alphabets such that those alphabets which fall into the group {a,b,c,d} can be counted as 1, then those in the group {e,f,g,h} are another lot "1", and so on? Currently, the BinCounts work only for numbers as shown below:

BinCounts[{1, 3, 2, 1, 4, 5, 6, 2}, {0, 10, 1}]  

 (* {0, 2, 2, 1, 1, 1, 1, 0, 0, 0} *)

BinCounts[{a, b, c, d, e, f, g}, {0, 6, 1}]

(* {0, 0, 0, 0, 0, 0} *)

I guess one way is to link each alphabet to a number, but yet to find a right way to do this.

$\endgroup$
  • $\begingroup$ What do you mean by are another lot "1"? $\endgroup$ – Dr. belisarius Sep 4 '15 at 5:09
  • $\begingroup$ Something like this? BinCounts[{a, b, c, d, e, f, g} /. Thread[{a, b, c, d} -> 1] /. Thread[{e, f, g, h} -> 2], {0, 6, 1}] $\endgroup$ – Dr. belisarius Sep 4 '15 at 5:09
  • $\begingroup$ @Belisarius U got it!, pls shift your comment to ans $\endgroup$ – thils Sep 4 '15 at 5:30
3
$\begingroup$
bins = {{a, b, c, d}, {e, f, g, h}};
vals = {1, 2};
ruls = Flatten@MapThread[Thread[Rule@##] &, {bins, vals}];
set = {a, b, e, e, f};
BinCounts[set /. ruls, {0, 6, 1}]

(* {0, 2, 3, 0, 0, 0}*)

If you always want vals going from 1 to Length@bins, then you can do instead:

fun = Function[{r}, Position[bins, r][[1, 1]], Listable];
BinCounts[fun@set, {0, 6, 1}]

(* {0, 2, 3, 0, 0, 0}*)
$\endgroup$
4
$\begingroup$

I would use the new associations functions.

letters = {a, b, c, d, e, f, g};    
groups = {{a, b, c, d}, {e, f, g, h}};

asc = Counts[letters]
(* <|a -> 1, b -> 1, c -> 1, d -> 1, e -> 1, f -> 1, g -> 1|> *)

Total /@ DeleteMissing /@ Map[asc, groups, {2}]

This should be fast assuming that letters is large and groups is small (since there are only so many letters).

For version 9, I'd build it with Tally.

$\endgroup$
  • $\begingroup$ Sorry, I don't understand. The OP asked for a BinCounts implementation, which have some additional syntax forms I believe you aren't covering. $\endgroup$ – Dr. belisarius Sep 4 '15 at 12:26
  • $\begingroup$ Able to extend @Szabolics to word structures: words = {ate, boy, cat, dog, eat, fat, go, hat}; groups = {{ate, boy, cat}, {dog}, {eat, fat}, {go, hat}}; asc = Counts[words] Total /@ DeleteMissing /@ Map[asc, groups, {2}] with output (* 3,1,2,2 *) $\endgroup$ – thils Sep 4 '15 at 12:45
  • 1
    $\begingroup$ @belisarius That's not what I thought he was asking. I though he wanted to count elements belonging to each group. "binning" makes no sense for objects that have no natural ordering. $\endgroup$ – Szabolcs Sep 4 '15 at 13:23
  • $\begingroup$ Ok, We understood the problem differently +1 $\endgroup$ – Dr. belisarius Sep 4 '15 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.