5
$\begingroup$
Query[All, <|"A" -> "a", "B" -> "b", "C" -> "c"|>] @ {
  <|"a" -> 1, "b" -> "x", "c" -> {1}|>,
  <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
  <|"a" -> 3, "b" -> "z", "c" -> {3}|>,
  <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,
  <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,
  <|"a" -> 6, "b" -> "z", "c" -> {}|>} 

It renames all the column headers from lower-case letters to upper-case letters. And works. But the rules appear reversed to me, which means I'm not thinking about it right. See ref/Query in the Documentation Center for the source of this example. If I could understand this, I would understand Query better.

$\endgroup$
10
$\begingroup$

This is "ascending" sub-query operator syntax. It operates on the entire row to produce a new row with the specified keys and values as the operator applied to the row.

However, the operators in the sub-query are strings so Query employs some syntax sugar to reduce the amount of code needed to be written.

So for

"A" -> "a"

Query's syntax sugar "interprets" the operator not as "a" but as

GeneralUtilities`Slice["a"]

This is an internal function that when applied to the row the value associated with key "a" is returned.

GeneralUtilities`Slice["a"]@<|"a" -> 1, "b" -> "x", "c" -> {1}|>
1

This results in the keys being renamed in the association returned.

This is less verbose and some would say easier to read (once you know about the syntax sugar) than the alternative. For example

Query[All, <|"A" -> #"a", "B" -> #"b", "C" -> #"c"|>&]

Also because &'s operator precedence means that additional brackets often need to be included to prevent it from capturing the additional expressions when chaining operators together in Query with /*.

Note that you can always view what Query will do with Normal. Although it does not always return standard Wolfram Language functions; current case in point.

Query[All, <|"A" -> "a", "B" -> "b", "C" -> "c"|>] // Normal
Map[
 GeneralUtilities`ApplyThrough[
  <|
   "A" -> GeneralUtilities`Slice["a"],
   "B" -> GeneralUtilities`Slice["b"],
   "C" -> GeneralUtilities`Slice["c"]
   |>
  ]]

Hope this helps.

| improve this answer | |
$\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.