3
$\begingroup$

Let's say I have the following nested dataset:

SeedRandom[14];
data=Transpose@Dataset@AssociationThread[{"a","b"},RandomInteger[{0,20},{2,50}]];
data=data[All,<|#,"combine"-><|"c"->Slot@"a"*2,"d"->Slot@"a"-Slot@"b"|>|>&]

enter image description here

I want to selectively apply a function, say f, onto the nested column c and keep the structure of the original dataset. Currently, I used the following to do it.

Dataset[Transpose[  (Transpose@data)[<|#, "combine" -> Normal@data[All, "combine", {"c" -> f}]|> &]  ] ,  MaxItems -> 5]

enter image description here

I found in the Dataset doc that dataset[All,{n->f}] can selectively map f onto the n^th column, which worked for col b.

Dataset[data[All, {"b" -> f}], MaxItems -> 5]

However, when I applied the following. Only the innermost subdataset was updated/returned.

Dataset[data[All, "combine", {"c" -> f}], MaxItems -> 5]

enter image description here

Is it possible to correct this? I also wonder is there any other way to return what I wanted. Thanks.

$\endgroup$
2
  • 2
    $\begingroup$ MapAt[f, data, {All, 3, 1}] ? $\endgroup$
    – Ben Izd
    Commented May 20, 2021 at 14:52
  • 1
    $\begingroup$ @BenIzd Thanks! I modified a little MapAt[f, data, {All, "combine", "c"}] to better suit my data. $\endgroup$
    – user34223
    Commented May 20, 2021 at 14:59

1 Answer 1

3
$\begingroup$

We can express the desired operation by using nested subquery operators:

data[All, {"combine" -> {"c" -> f}}]

dataset

$\endgroup$
1
  • $\begingroup$ This is the answer I expected when posted the question. I just don't know how to nest it. I tried something like {"combine"/"c"->f} or {#combine,#c}->f but no luck:). Following this structure, I guess I can apply it to the even deeper layer by {"key1"->{"key2"->{"key3"->f}}}? Thanks again! $\endgroup$
    – user34223
    Commented May 21, 2021 at 2:40

Your Answer

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