A friend asked me a few days ago how can he get the sum of all fields in a layer. He had a layer where all the fields were numeric and he wanted to create a sum like R's dplyr::across allows. Now that's an interesting question, not because it's a common problem, but because it got me thinking about automatically accessing fields in a QGIS layer, i.e. without knowing field names.
We can get the values of all of our fields with a relatively simple expression:
map_avals( attributes()),
try( to_real( @element),false)
)
map_avals( attributes()),
@element = 0 or try( to_real( @element),false)
)
array_filter(
map_avals( attributes()),
@element = 0 or try( to_real( @element),false)
)
)
You can also use map_akeys(attributes()) and wrap that in a for loop since attributes is a dictionary\JSON of the current feature, and that might be a subject for another post, but not today.
You
can check out the other posts in this series and learn more about the QGIS
expression engine, and if you have your own cool uses for expression
I'd love to hear about them in the comments.
Exploring The QGIS Expression Engine, Part 1: Getting Values From JSON & HSTORE
Exploring The QGIS Expression Engine, Part 2: What's Missing From Select By Location
Exploring The QGIS Expression Engine, Part 3: Writing Custom Expression Functions
Exploring The QGIS Expression Engine, Part 5: Fun With Arrays
Exploring The QGIS Expression Engine, Part 6: Creating And Using Variables
Exploring The QGIS Expression Engine, Part 7: Cross-Layer RelationshipsExploring The QGIS Expression Engine, Part 8: Expression Controlled Styles
Comments
Post a Comment