# Replacing single location by mean of duplicate locations using R

I would like to apply kriging with a set of heavy metals Belgian data.

But I have a duplicate location :

``````length(clean.donnees.Ni@coords)
[1] 5740
length(unique(clean.donnees.Ni@coords))
[1] 5186
``````

As far as I understand, the `sp::zerodist` function simply removes all the points we the same location.

Is there a way to take the mean of those points instead of simply remove them ?

I tried with different packages such as `dplyr::group_by`, but because location is represented by two columns, I couldn't resolve it.

I also found the exact same question but there is still no answer :

Dealing with duplicate locations when kriging by replacing them with single location taking mean of duplicates using R

Accessing coordinates of a `sp` object through `dplyr::group_by()` and `@` may be a bit cumbersome, because coordinates are in a separate slot than the rest of the variables.

The following code starts with a plain data frame where coordinates are in the same table and then gets passed through `group_by` and `summarize`. After this procedure you should be able to convert to `sp` object (with `coordinates(df) <-`) or, even better, to `sf` object with `st_as_sf(df)`. `sf` objects work very well with `dplyr`.

``````library(sf)
library(sp)
library(dplyr)

data("meuse")

df = meuse[, c("x", "y", "cadmium")] # let's just use one variable

df2 = df[sample(1:10, size = 20, replace = TRUE),]   # we create a subset for repeating coordinates
df2\$cadmium = runif(20,1,9)                          # we change cadmium values with random numbers

rbind(df, df2) %>%         # put dataframes together
group_by(x, y) %>%
summarise(mean_cad = mean(cadmium), n_coords = n()) %>% # n() is for looking duplicate number
arrange(desc(n_coords)) %>%
st_as_sf(coords = c("x", "y"), crs = 28992)  # convert to sf object, crs is from ?meuse
``````
• Ok that clear, but I would like to keep only the mean for a given location. Maybe can I do something like : `df <- df %>% group_by(x,y) %>% summarise(Ni = mean(Ni))` ? I drastically reduced my variable number but do you know if this manip is truly saving the mean of the Ni data ? Dec 15, 2021 at 16:08
• yes, you may pass `(mean(Ni, na.rm = TRUE))` if you have NAs Dec 16, 2021 at 23:27