3
$\begingroup$

I know that it is the standard functionality of Merge to combine the values of the same keys among associations.

Now I would like to deal with a situation in which, in my associations, the keys are strings (English words). And I want to define the sameness as two words having the same result from WordStem so that "effects" and "effect" are the same key.

So is it possible for Merge to accept such a same test function for the keys, e.g., Equal@@WordStem[{##}]&, to determine what keys should be considered the same and be merged?


A MWE goes as below:

mergeFunc = x \[Function] {Total[#], Union[Flatten@#2]} & @@ (x\[Transpose]);

Merge[{<|"effect" -> {5, {2, 3}}|>, <|"effects" -> {4, {1, 3, 5}}|>}, mergeFunc]

Merge[{<|"effect" -> {5, {2, 3}}|>, <|"effect" -> {4, {1, 3, 5}}|>}, mergeFunc]
<|"effect" -> {5, {2, 3}}, "effects" -> {4, {1, 3, 5}}|>

<|"effect" -> {9, {1, 2, 3, 5}}|>

The second result is desired.


Additional requirement: no new keys should be introduced.

For example, what if I now have "apple" and "apples" as the keys instead of "effect" and "effects"?

That means I need the word stems as the criterion but not as the keys in the merged result.

$\endgroup$
  • $\begingroup$ Can you give example associations? $\endgroup$ – J. M. is away Oct 19 '18 at 14:05
  • $\begingroup$ @J.M.iscomputer-less Please see the update. $\endgroup$ – Αλέξανδρος Ζεγγ Oct 19 '18 at 14:13
5
$\begingroup$
 data = {<|"effect" -> {5, {2, 3}}|>, <|"effects" -> {4, {1, 3, 5}}|>};
 Merge[KeyMap[WordStem]/@ data, mergeFunc]

<|"effect" -> {9, {1, 2, 3, 5}}|>

Also

 GroupBy[ data, First @* WordStem @* Keys -> First, mergeFunc]  

 <|"effect" -> {9, {1, 2, 3, 5}}|>

$\endgroup$
3
$\begingroup$

What about this?

data = <|"effect" -> {5, {2, 3}}, "effects" -> {4, {1, 3, 5}}|>;
Merge[
 KeyValueMap[{key, value} \[Function] WordStem[key] -> value, data],
 mergeFunc
 ]

<|"effect" -> {9, {1, 2, 3, 5}}|>

$\endgroup$

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.