I am trying to run my code in R for a spatial weights matrix, but the following error shows up. I think it's got something to do with my data, but I'm not sure how to resolve it.

nb = st_contiguity(no2_pop_join, queen = TRUE)
wt = st_weights(nb, style = "W", allow_zero = TRUE)

no2_pop_join <- no2_pop_join |> 
  mutate(nb, wt)

! Problem while computing ..1 = nb. x ..1 must be size 12 or 1, not 960.


1 Answer 1


Please "always" indicate which libraries you are using. The below syntax works so, it is likely something with your data, potentially empty sets. Have you looked at the dimensions of your respective matrices? You are really not providing enough information for us to troubleshoot beyond that. For further assistance, you could provide a reproducible example or a link to the problem data at hand.


( guerry <- guerry |>
 mutate(nb = st_contiguity(geometry, queen = TRUE),
        wt = st_weights(nb, style = "W", allow_zero = TRUE),
        .before = 1) )

Perhaps if you indicated your eventual goal or expected outcome here we could provide a different approach. There is the rgeoda library that also provides Nth-order neighbor contingency and autocorrelation functions. The outcome in your code is adding the weights and neighbor lists to the sf polygon object. If you look at str(guerry), after the above functions are applied, the result is that the nb and wt columns are lists object, still retaining the sfdep classes ("nb") and not one-to-one row-column variables. Lists embedded as columns are quite difficult to work with. Is this, in fact, what you are after? You are just as well served just keeping the objects separate and not incorporating them into the sf polygon object.

  • Thanks. But I come across another error.Error in stopifnot(): ! Problem while computing nb = st_contiguity(geometry, queen = TRUE). i The error occurred in group 152: GeoUID = "5370201.00". Caused by error in sum(): ! invalid 'type' (list) of argument Backtrace: 1. dplyr::mutate(...) 10. sfdep::st_contiguity(geometry, queen = TRUE) 11. spdep::poly2nb(geometry, queen = queen, ...) Apr 12, 2023 at 16:40
  • library(dplyr) library(sfdep) Yes these are the packages Apr 12, 2023 at 18:17
  • The data is my own data from experiments Apr 12, 2023 at 18:17
  • Try the commands with example data provided. If that fails, it's probably your data type/format that's the issue, such as how you are importing it from .xls or other format.
    – Mox
    Apr 12, 2023 at 20:21
  • Yeah it worked with the example data. I'm not sure what the issue is Apr 12, 2023 at 20:45

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.