I have a polygon layer. I would like to select every second row of the polygons but not manually. Is there an expression to select every second row as seen on the picture with Select by expression in QGIS?
*(Numbers refer to the polygon's "ID")
You can use the
floor function in your expression, like this:
floor($id /24) IN (1,3,5,7,9,11,13,15,17,19,21)
On a sample grid I've obtained this result with my own numbers (my grid has 13 columns per row):
floor($id/13) IN (1,3,5,7,9)
So, in general:
floor($id / number_of_columns) IN (1, 3, 5, ..., 2*number_of_rows_to_be_selected - 1)
To select exactly the other rows (i.e., 1st, 3rd, and so on) you would use:
floor($id /24) IN (0,2,4,6,8,10,12,14,16,18,20,22)
floor($id / number_of_columns) IN (0, 2, 4, ..., 2*number_of_rows_to_be_selected)
Does it make sense?
EDIT: Improved answer
Thanks to @ndawson, who suggests a shorter version of the selection expression. In summary, you could use:
floor($id / number_of_columns) % 2 = 1
to select 2nd, 4th, 6th, ... rows, or:
floor($id / number_of_columns) % 2 = 0
to select 1st, 3rd, 5th, ... rows.
You can use the "select by expression" geoalgorithm with an expression like id>= and id<=24 or id>=49 and id<=72..... Since the cell values seem to be numbered by standard count laterally, it shouldn't be a problem to figure out the ranges you need even if your data set contains more rows than listed above.
Make sure the layer you wish to choose is highlighted in the Layer Control Box Then using the Select By Expression button
Type what you see in the picture into the Expression Box.
It should look like this when you are finished
(( "ID" ) - 1) % 24 = 0
If the expression is correct you will see a result in the bottom of the Expression Builder Dialog that does not "Expression is Invalid" in red letters.
ID is the name of the field you wish to select, the first polygon of each row minus 1 is divisible by 24.
% is the modulo function, it will take the number immediately following, and divide the ID -1 number by it. If the remainder is not 0, the polygon is not chosen.
Ignore the error displayed in the above picture, I just did this with a table that was not a grid, and did not have a field named ID.