*資料前處理
library(sf);library(tmap);library(spdep)
setwd("D:/1092SA/Data")
TW=st_read("Popn_TWN2.shp",options="ENCODING=BIG5")
old=TW$old=TW$A65UP_CNT/(TW$A0A14_CNT+TW$A15A64_CNT+TW$A65UP_CNT)
qtm(TW,'old',fill.title="高齡人口比例")
TW.nb = poly2nb(TW)
TW.nb.w = nb2listw(TW.nb,zero.policy=T)
LISA = localmoran(old, TW.nb.w,zero.policy = T,alternative = "two.sided")
z=LISA[,4]
p=LISA[,5]
diff=old-mean(old)
col=c()
col[z>0 & diff>0]="red"
col[z>0 & diff<0]="blue"
col[z<0 & diff>0]="pink"
col[z<0 & diff<0]="lightblue"
col[p>0.05]="grey90"
TW$colI=col
qtm(TW,'colI')+tm_add_legend("fill",labels=c("HH","LL","HL","LH","NS"),col=c("red","blue","pink","lightblue","grey90"))
TW.nb.in = include.self(TW.nb)
TW.nb.w.in = nb2listw(TW.nb.in)
TW$Gi = localG(old,TW.nb.w.in)
TW$colG="grey90"
TW$colG[TW$Gi>=qnorm(.95)]="red"
qtm(TW,'colG')+tm_add_legend("fill",labels=c("cluster","no-cluster"),col=c("red","grey90"))
LISA. = localmoran(old, TW.nb.w,zero.policy = T)
p=LISA.[,5]
TW$colHH="grey90"
TW$colHH[p<0.05 & diff>0]="red"
p.adj=p.adjust(p,"fdr")
TW$colHHfdr="grey90"
TW$colHHfdr[p.adj<0.05 & diff>0]="red"
HH=tm_shape(TW,xlim=c(146500,351000),ylim=c(2400000,2850000))+tm_polygons(col='colHH')
HH.fdr=tm_shape(TW,xlim=c(146500,351000),ylim=c(2400000,2850000))+tm_polygons(col='colHHfdr')
tmap_arrange(HH,HH.fdr)
TW$colG.="grey90"
TW$colG.[TW$Gi>=qnorm(1-.05/nrow(TW))]="red"
qtm(TW,'colG.')