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

But I have a duplicate location :

[1] 5740
[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

1 Answer 1


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.



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 ?
    – Jouline
    Dec 15, 2021 at 16:08
  • 1
    yes, you may pass (mean(Ni, na.rm = TRUE)) if you have NAs
    – Elio Diaz
    Dec 16, 2021 at 23:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.