0

Still getting used to the language of GIS with R so please bear with me.

I have this public dataset.

It has two levels of political boundaries: ADM1 and ADM2.

I am currently doing everything (i.e. plotting, calculations, etc.) for ADM2 which is each of the 2,440+ municipalities in Mexico because that is how the geometry is determined. However, I would like to calculate averages per states (ADM1) and start working with those by sort of "dissolving", if you will, the geometry of municipalities (ADM2) into geometries of (ADM1).

So far I have imported it:

library (sf)
library (dplyr)

mexi_sf<-read_sf( dsn = getwd()
       , layer = "MexicoCaseStudy"
       , stringsAsFactors = FALSE ) 

Fixed some labels and changed some classes:

 mexi_sf$ADM1NAME<-str_replace_all(mexi_sf$ADM1NAME, 
                c("M.xico" = "México", "Nuevo Le.n" = "Nuevo León","San Luis Potos."="San Luis Potosí","Quer.taro de Arteaga"="Querétaro de Arteaga"))
mexi_sf$ADM1NAME<-as.factor(mexi_sf$ADM1NAME)
mexi_sf$ADM2NAME<-as.factor(mexi_sf$ADM2NAME)
mexi_sf$ADM1CODE<-as.numeric(mexi_sf$ADM1CODE)
mexi_sf$ADM2CODE<-as.numeric(mexi_sf$ADM2CODE)

Changed some outliers:

  for (row in 1:nrow(mexi_sf)){
    if (mexi_sf$FOODEXP[row]==-9999){
     mexi_sf$FOODEXP[row]=-1
    }}

Here is my attempt to average the variable FOODEXP by ADM1NAME.

  average_food_exp<-mexi_sf%>%
  group_by(ADM1NAME)%>%
  mutate(meanFOODEXP=mean(FOODEXP))

And obvs something is wrong because I can't plot it:

    big_food_map_sf_trial<-tm_shape(average_food_exp,style="quantiles",n=8)+
  tm_fill(col="meanFOODEXP",palette="Reds",title="mean FOODEXP (MXN 2004)")+
  tm_text("ADM1NAME",size=0.5)+
  tm_layout(legend.outside =FALSE)+
   tm_borders(col="black")+
  tm_credits("Source: CIMMYT, June 2004, Mexican municipalities below food poverty line, year 2000.",position=c("left","bottom"),size=0.75)

save_tmap(tm=big_food_map_sf_trial,filename="big_food_map_sf_trial.png",width = 17,height=7)

Any ideas on how to proceed?

1

I think you need summarize(meanFOODEXP=mean(FOODEXP)) (not mutate) after the group_by.

E.g.

library(sf)
example(st_read)  ## to read 'nc' object
nc %>% group_by(row_number() %% 4) %>% summarize(mean(BIR74)) 

I just make a 4-group dummy there, but you should be able to do

average_food_exp<-mexi_sf%>%
group_by(ADM1NAME)%>%
 summarize(meanFOODEXP = mean(FOODEXP)) 

It's always a good idea to ungroup afterwards if you only mutate, because that maintains the rows (and the groups) but applies the summary value to the original rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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