5
$\begingroup$

What I am trying to do is to add columns titles into my data set that has unit information.
First I create a list of countries:

Countries = {"UnitedStates", "Mexico", "Canada", "Brazil","Argentina", "Peru", "Ecuador", "CostaRica", "ElSalvador"}

Then I compute for each country the population using CountryData.

populations = CountryData[#, "Population"] & /@ Countries

Now I proceed to create and association and then then data set.

dat = Dataset[AssociationThread[Countries -> populations]]

enter image description here

But when I try to add names to columns using dat[All, <|"1" -> "Country", "2" -> "Population"|>] I get this error. enter image description here

$\endgroup$
8
$\begingroup$

I think what you need is more like this:

dat=Dataset[MapThread[<|"Country" -> #1,"Population" -> #2|> &, {Countries, populations}]]

enter image description here

The structure you are looking for is one association per row, with the keys equal to the column headings.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Yeah it worked nice. $\endgroup$ – Las Des May 2 at 20:37
  • 2
    $\begingroup$ A more natural way to do this is to use AssociationThread[]: Dataset[AssociationThread[{"Country", "Population"}, #] & /@ Transpose[{Countries, populations}]] $\endgroup$ – J. M.'s discontentment May 3 at 10:59
3
$\begingroup$

One option could be

 PrependTo[dat, <|"Country" -> "Population"|>]

Mathematica graphics

I do not know how the semantics of your data set will change now by adding the title right into the data itself like this. I think normally column titles are added at the end, for display purposes and not part of the actual dataset itself.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Yes that correct, I am using this as an example. $\endgroup$ – Las Des May 2 at 19:40

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.