Peter, this is my take on the data query.
I like to split a complex query into serialized queries, each of which addressing a specific need.
This as opposed to a nested query notation.
Filtering the planets with one or more moons can be done as follows:
(Note that this is rather trivial as we only need to remove the planets Mercury and Venus)
I like to split a complex query into serialized queries, each of which addressing a specific need.
This as opposed to a nested query notation.
Filtering the planets with one or more moons can be done as follows:
(Note that this is rather trivial as we only need to remove the planets Mercury and Venus)
In[]:=
planets=ExampleData[{"Dataset","Planets"}];
In[]:=
Select[Length@Keys@#Moons>=1&]@planets
Out[]=
Next, we need to remove any moons with missing masses or we get into trouble with the density calculation later:
Query[All,<|#,"Moons"->Select[!MissingQ@#Mass&]@#Moons|>&]@planets
Out[]=
Let’s create a constant of the Earth’s moon density:
In[]:=
moondensity=Query["Earth","Moons",1,"Mass"]@planetsPiQuery["Earth","Moons",1,"Radius"]@planets^3;
4
3
Now let’s create a dataset with the moons density relative to the Earth’s Moon with all of the above filters applied:
In[]:=
QueryAll,<|#,"Moons"->QueryAll,<|"Density"->#MassPi#Radius^3moondensity|>&@#Moons|>&@Query[All,<|#,"Moons"->Select[!MissingQ@#Mass&]@#Moons|>&]@Select[Length@Keys@#Moons>=1&]@planets
4
3
Out[]=
Note: I changed the dataset by adding the column density in place of the mass and radius columns. This simplified my query and removes redundant information.
BTW: If you want to sort the moons by density, this is how you can do it:
In[]:=
Query[All,<|#,"Moons"->ReverseSortBy[#Density&]@#Moons|>&]@%
Out[]=
Putting it all together
Putting it all together
To wrap it all up, let’s create a comprehensive overview of all planets with moons with more than 0.55 of the Earth’s Moon density.
At last, I will create a separate dataset of the corresponding planets radii.
Note: if the selection of the moons density yields in none, it will create an empty row in the Moons section. Therefore I have to remove the planet with no moon results with Select[Keys@#Moons!={}&]
At last, I will create a separate dataset of the corresponding planets radii.
Note: if the selection of the moons density yields in none, it will create an empty row in the Moons section. Therefore I have to remove the planet with no moon results with Select[Keys@#Moons!={}&]
In[]:=
Query[All,KeyDrop["Mass"]]@Select[Keys@#Moons!={}&]@Query[All,<|#,"Moons"->Select[#Density>0.55&]@#Moons|>&]@QueryAll,<|#,"Moons"->QueryAll,<|"Density"->#MassPi#Radius^3moondensity|>&@#Moons|>&@Query[All,<|#,"Moons"->Select[!MissingQ@#Mass&]@#Moons|>&]@Select[Length@Keys@#Moons>=1&]@planetsQuery[All,{"Radius"}]@%
4
3
Out[]=