3
$\begingroup$

I have a relatively simple dataset that provides a list of values for a list of countries:

data = Dataset[{<|"GeoAreaName" -> Entity["Country", "Canada"], 
    "Value" -> 5.2|>, <|
    "GeoAreaName" -> Entity["Country", "Swaziland"], "Value" -> 398|>, 
     <|"GeoAreaName" -> Entity["Country", "SouthAfrica"], 
    "Value" -> 781|>, <|
    "GeoAreaName" -> Entity["Country", "Switzerland"], "Value" -> 7.8|>, 
     <|"GeoAreaName" -> Entity["Country", "UnitedStates"], 
    "Value" -> 3.1|>}]

I am wanting to thread the values from the first key to the values of the second key so that I get:

{Entity["Country", "Canada"] -> 5.2, Entity["Country", "Swaziland"] -> 398, Entity["Country", "SouthAfrica"] -> 781, Entity["Country", "Switzerland"] -> 7.8, 
 Entity["Country", "UnitedStates"] -> 3.1}

I am able to do this with the following code:

Thread[Normal[data[[All, 1]]] -> Normal[data[[All, 2]]]]

While it works fine, I look at the code and think there must a simpler way that doesn't require me to first extract two lists and then recombine.

The actual code I am working on has quite a few more complexities than what I have listed here, so any simplification I can find will be greatly multiplied across all the work.

Curious if I am taking the long way around or if there is something more straight forward

$\endgroup$
2
$\begingroup$

Perhaps

Rule @@@ data

enter image description here

Normal[Rule @@@ data]

enter image description here

If you have more than two columns and you want to link two of them with Rule you can do

data[Rule @@@ # &, {"GeoAreaName", "Value"}] (* or *)
Rule @@@ data[All, {"GeoAreaName", "Value"}]

or data[Rule @@@ # &, {1, 2}] if "GeoAreaName" and "Value" are first two columns.

Notes:

  • Rule @@@ data and data[Rule @@@ # &] and Rule @@@ Values @ data give the same result.
  • Rule @@@ Normal @ data and Normal[Rule @@@ data] give the same result.
$\endgroup$
1
$\begingroup$

What about

Rule @@@ Values@Normal@data

?

$\endgroup$
1
$\begingroup$

You may use Query implicitly on the Dataset.

With data as in the OP.

data[All, Apply[Rule]]

Mathematica graphics

Or, for the entities as the keys.

data[Association, Apply[Rule]]

Mathematica graphics

You can enter the entity keys in natural language using Ctrl+=, typing the country name, and then hitting the normal Enter key (i.e. not the one on the number pad).

Hope this helps.

$\endgroup$
1
  • $\begingroup$ It is very helpful to see multiple solutions to the same problem. While using Rule@@@data answers the question exactly as I asked it, I have flagged your code in my "cheat sheet" for data manipulation because I am sure to use it in the future! $\endgroup$
    – kickert
    Jul 14 '18 at 1:53

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.