5

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:

enter image description here

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.

enter image description here

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.

asked Feb 6, 2019 at 18:36

1 Answer 1

11

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")
answered Feb 6, 2019 at 18:41
1
  • Hit that green check mark :) Commented Feb 22, 2022 at 20:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.