# Calculating number and sum of length for linear objects inside polygon

I have two shapefiles.

• the first includes Polygons. Each polygon has a unique `"FID"`
• the second has linear objects that belong exclusively to one of these polygons and they also have a `"CLASS"` attribute which takes values 1 to 6 and a `"LENGTH"` attribute

For each of the polygons I need to calculate the number of linear objects that have a class value = 1, the number of linear objects that have a class value = 2 and so on.

Also for each of these classes that belong to each polygon I need the sum of their length.

For example, in the end i need to have in the polygon shapefile these values, i.e. each polygon will have 12 new values:

``````"FID", "Count1", "Count2", ..., "Count6", "SUM1", "SUM2", ..., "SUM6"
``````

Is there any easy way to do this or do I have to try ArcPy?

• Intersect - Summary statistics
– BERA
Jun 7, 2020 at 4:51

In QGIS, you can

1. Run Intersection (Processing Toolbox, QGIS, Vector overlay) with the line dataset as Input layer and the polygon dataset as Overlay layer. Use an Overlay fields prefix if `FID`, `CLASS` or `LENGTH` are present in both datasets.
2. Run Statistics by Categories on the resulting line layer.

Choose the `LENGTH` field as Field to calculate statistics on, and select the polygon id (`FID`) field and the `CLASS` field as Field(s) with categories (multiple selection).

3. Remove the fields that you are not interested in from the resulting table.

4. This table now includes the statistics you need. You can use that to calculate the fields you were after using selection and the field calculator, and then trim the table to only include one line per polygon (the table has to have unique values in the `FID` field).

5. Join the table to the polygon layer (layer properties-> Join) using the polygon id (`FID`) as join field.

The polygon layer now includes the statistics you were after.

I would try to do this in Excel / LibreOffice Calc!

1. Prepare the columns you need in QGIS
2. Open the dbf files of the two shapefiles in Excel / LibreOffice Calc
3. Copy the content of the line dbf file as a second table into your polygon dbf file
4. It should be easy to calculate the values you need with the functions "COUNTIFS" and "SUMIFS"