Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Allow nth_value to take a column as the 'nth' argument #375

Open
ae3e opened this issue Oct 8, 2024 · 2 comments
Open

Allow nth_value to take a column as the 'nth' argument #375

ae3e opened this issue Oct 8, 2024 · 2 comments
Labels
enhancement New feature or request

Comments

@ae3e
Copy link

ae3e commented Oct 8, 2024

I would like to use the nth_value function with a nth parameter coming from an another column (see the example below).
But it fails. I don't really know if it's the expected behavior or if there's something wrong?

aq
  .table({
    value: [69, 108, 178, 207, 253, 268, 312, 281, 221, 142, 72, 52],
    index: [3, 2, 3, 5, 6, 8, 2, 2, 7, 5, 4, 5]
  })
  .derive({
    nth: (vv) => aq.op.nth_value(vv.value, vv.index)
  })

gives an error RuntimeError: data is not defined

nth always has to be a constant?

@jheer
Copy link
Member

jheer commented Oct 8, 2024

Thanks for posting. Yes, currently nth has to be an externally provided value, such as a constant or parameter. I will mark this as a feature request to enable column values as arguments as well.

@jheer jheer added the enhancement New feature or request label Oct 8, 2024
@jheer jheer changed the title Error when using nth_value with nth defined in an another column Allow nth_value to take a column as the 'nth' argument Oct 8, 2024
@ae3e
Copy link
Author

ae3e commented Oct 8, 2024

Thanks for your answer and this great lib,

In the meantime, I finally tried to add my first custom function.
Seems to work but I still have to do dig a little more...

aq.addWindowFunction(
  "my_nth_value",
  {
    create: () => ({
      init: () => {}, // No initialization needed
      value: (window, columns) => {
        let value1 = window.value(window.index, columns)[1];
        value1 = +value1;
        if (!(value1 >= 0))
          throw Error("nth_value nth must be equal or greater than zero.");

        const i = window.i0 + value1;
        return i < window.i1 ? window.value(i, columns)[0] : null;
      }
    }),
    param: [2] // 2 field inputs, 0 extra parameters
  },
  { override: true }
);

and a simple use case

aq
  .table({
    value: [69, 108, 178, 207, 253, 268, 312, 281, 221, 142, 72, 52],
    index: [3, 2, 3, 5, 6, 8, 2, 2, 7, 5, 4, 5]
  })
  .derive({
    nth: (vv) => aq.op.my_nth_value([vv.value, vv.index])
  })

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants