As discussed in this question, QGIS automatically saves recently used expressions in the field calculator. But recently used expressions are deleted after a while. Sometimes I need to re-use an expression that I used a while ago, and it's no longer available.
So I needed a way to store expressions for re-use in the Field Calculator at a much later time.
The method I figured out is to store the expression as in a text field. When I need to re-use the expression, I copy it from the attribute table into the Field Calculator. Here's what that looks like with a simple example:
Of course it's trivial to remember and re-enter the expression in this example. I would use this method with much more complicated expressions, such as "Population"/$area*3.58701e-8/"Population"
, which calculates population density (people per square mile) after first converting square feet to square miles.
Now I'm looking for a better way than manually copying the expression. It seems like there should be a way in the Field Calculator to take the field name as input, interpret it as an expression, and output the result of that expression. Here's what I've tried so far:
Just using the field name outputs the formula as a string.
Is there a function that will force the Field Calculator to interpret a string as an expression? By comparison to the expressions to_real()
and as_string()
, I'm thinking it would be something like as_expression()
or as_formula()
. So the output of as_expression('$area')
would be the calculated area of the polygon feature.
1 Answer 1
I found the answer to my own question almost as soon as I posted it. The function I was looking for is called eval
.
function eval
Evaluates an expression which is passed in a string. Useful to expand dynamic parameters passed as context variables or fields.
Syntax eval(expression)
Arguments
expression an expression string
Examples
eval(''nice'')
→ 'nice'eval(@expression_var)
→ [whatever the result of evaluating @expression_var might be...]
So for my example where an expression is stored as a string in a field called "Expression", use this in the Field Calculator:
eval("Expression")
-
Hit that green check mark :)bugmenot123– bugmenot1232022年02月22日 20:58:27 +00:00Commented Feb 22, 2022 at 20:58