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.

 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}}|>

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}}|>

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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