5
$\begingroup$

I currently have a dataset, and I would like to add a column based on another list.

For example:

ds = Dataset[{<|"name" -> "bob"|>, <|"name" -> "joe"|>}];
ages = {1,2};

I want to get

Dataset[{<|"name" -> "bob", "age"->1|>, <|"name" -> "joe", "age"->2|>}];

I was thinking of using MapIndex, but I don't really know how to make reform the results into a dataset again, and it seems wasteful.

How can I do this?

$\endgroup$

2 Answers 2

6
$\begingroup$
ds[MapIndexed[Append[#1, "age" -> ages[[First@#2]]] &]] 
{<|"name" -> "bob", "age" -> 1|>, <|"name" -> "joe", "age" -> 2|>}

Note 10.0.2 throws a warning - who knows what's going on in that private type system:

 First::normal: Nonatomic expression expected at position 1 in \
First[TypeSystem`ZSignatures`PackagePrivate`i]
$\endgroup$
9
  • $\begingroup$ Do you mind explaining how this works? What is the First function doing (I understand the rest) $\endgroup$
    – soandos
    Commented Feb 5, 2015 at 4:58
  • $\begingroup$ MapIndexed works on multidimensional arrays. MapIndexed[f, ages] gives {f[1, {1}], f[2, {2}]}. If ages were, say, a 2-dim array, then the indexes would be {i,j}. In this problem, First picks out the rows of ages. $\endgroup$ Commented Feb 5, 2015 at 5:03
  • $\begingroup$ ah, got it. Thank you. $\endgroup$
    – soandos
    Commented Feb 5, 2015 at 5:04
  • 4
    $\begingroup$ +1 We can dodge the warning message in 10.0.2 using something like ds[MapThread[Append[#, "age" -> #2 ] &, {#, ages}] &]. Messages like this are due to some serious evaluation leaks in the 10.0.2 type system code :( $\endgroup$
    – WReach
    Commented Feb 5, 2015 at 5:24
  • 2
    $\begingroup$ Are you a beta tester for 10.0.3 or is that a typo? $\endgroup$
    – Mr.Wizard
    Commented Feb 5, 2015 at 8:18
2
$\begingroup$

Try this:

    Dataset@MapThread[
  Append, {Normal[ds], Association["age" -> #] & /@ ages}]

yielding the following:

enter image description here

Have fun!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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