How to dynamically evaluate row-specific formulas

I'm trying to implement dynamic formula evaluation per row in DolphinDB, where each row contains its own calculation expression. Here's my current approach:
I've created a table with a column v storing formulas:
t = table(
1 1.1 1.3 1.4 1.5 1.7 as a,
0.2 0.2 0.2 0.2 0.2 0.2 as b,
["iif(a>1,min(a-1,b),0)", "iif(a>1,min(a-2,b),0)",
"iif(a>1,min(a-3,b),0)", "iif(a>1,min(a-4,b),0)",
"iif(a>1,min(a-5,b),0)", "iif(a>1,min(a-6,b),0)"] as v
)
I attempted to evaluate these formulas using metaprogramming:
// Function to dynamically evaluate each row's formula
def calculateRow(row) {
return eval(parseExpr(row.v))
}
// Apply to each row
result = each(calculateRow, t)
t[`result] = result
However, I'm getting the error:
Server response: result = each(calculateRow, t) => calculateRow: return
eval(parseExpr(row."v")) => SQL context is not initialized yet
How can I properly implement this row-specific formula evaluation in DolphinDB? What's causing the "SQL context not initialized" error, and what's the correct way to handle dynamic expression evaluation per row?
Answer
You can leverage the dictionary assignment feature of parseExpr to dynamically evaluate row-specific formulas. Here's the working approach:
each(def(mutable d) -> parseExpr(d.v, d.erase!(`v)).eval(), t)
Output is :
0 0 -0.9 -1.7 -2.6 -3.5 -4.3
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions