Combine rows and sum values

Hi all,

Here is a sample from my data set:

    Shape_Area zelfstandi
4         1.57          1
5         2.10          2
6         2.24          2
8         2.10          7
10        2.10          5
12        3.34          1
15       26.23          a
17        0.39          a
19        0.75          a
20        2.24          5
23        2.24          6
24        2.24          7
27        2.12          6
32        1.57          8
33        2.10          9
34        2.24          9
36        2.10         10

I am trying to sum all the values in Shape_Area if the zelfstandi is similar.
I have no idea how to do this, could anyone help me?

Thanks :slight_smile:

If I understand you correctly, in particular the "zelfstandi is similar" bit, then maybe you can do as follows:

library(dplyr)

data %>%
  group_by(zelfstandi) %>%
  summarise(total_shape_area = sum(Shape_Area))

This will sum the Shape_Area for each distinct value of zelfstandi (by the way it looks quite weird that this variable is a mix of integers and strings)

1 Like

This is the data I got, but I could change the "a" to a number as well if that makes things easier.

Using your code gives me the following error

 no applicable method for 'group_by_' applied to an object of class "c('SpatialPolygonsDataFrame', 'SpatialPolygons', 'Spatial', 'SpatialVector', 'SpatialPolygonsNULL')"

Looks like your data is not a "regular" data frame which the dplyr verbs are meant for. Can you convert it to a class data.frame or tibble (which inherits from data.frame)?

That has been the solution, thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.