Wednesday 31 August 2016

How to re-use an expression, stored as a string, in QGIS Field Calculator


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.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...