4
$\begingroup$

Why does taking a Part fail in a Dataset query function when there is an operation in the index argument?

dataset = Dataset[Table[<|"a" -> n|>, {n, 3}]];

dataset[All, Range[4][[#a]]&]

enter image description here

dataset[All, Range[4][[#a + 1]]&]

enter image description here

To get it to work I need to use Extract instead:

dataset[All, Extract[Range[4], {#a + 1}]&]

enter image description here

Are there other workarounds?

$\endgroup$
2
$\begingroup$

This behavior is concerned with Association's HoldAllComplete attribute.

Attributes[Association]
{HoldAllComplete, Protected}

I am not completely certain of the internal workings but it appears that the a# + 1 expression is being held unevaluated when passed to Part. Wrapping the expression in Evaluate to force evaluation does not appear to help.

dataset[All, Range[4][[Evaluate[#a + 1]]] &]

Message: Plus[1, Atom[Integer]] is not a valid part specification.

However, you there is a workaround by passing the expression as a parameter to a pure function.

dataset[All, Range[4][[#]] &@(#a + 1) &]

enter image description here

Hope this helps.

$\endgroup$
2
$\begingroup$

How about

 ds = Dataset[Table[<|"a" -> n|>, {n, 3}]];
 ds[All, "a", # + 1 &]

ds

BTW, you 1st query can be simplified to

ds[All, "a"]
$\endgroup$

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.