library(spdep);library(rgdal);library(GISTools)
setwd("D:/1071QG/Fin")
KH=readOGR(dsn=".",layer="KH",encoding = "utf8")
KH$TOWN=as.character(KH$TOWN)
KH$KMT=as.numeric(as.character(KH$KMT))
KH$DPP=as.numeric(as.character(KH$DPP))
KDR=KH$KMT/KH$DPP
KH$KDR=KDR
#1
KH.nb=poly2nb(KH)
KH.nb.w=nb2listw(KH.nb)
KDR_LISA=localmoran(KDR,KH.nb.w)
M=mean(KDR)
KH$TOWN[KDR<M & KDR_LISA[,1]<0]
## [1] "鹽埕區" "前鎮區" "旗津區" "仁武區" "旗山區"
# 或
KH.nb.m=nb2mat(KH.nb)
KDR.near=KH.nb.m%*%KDR
KH$TOWN[KDR<M & KDR.near>M]
## [1] "鹽埕區" "前鎮區" "旗津區" "仁武區" "旗山區"
#2
KDR_LISA[14]
## [1] 0.02902576
xz=(KDR-mean(KDR))/sd(KDR)*sqrt(35/34)
xz[14]*sum(KH.nb.m[14,]*xz)
## [1] 0.02902576
# 或
# KDR_LISA.adj=localmoran(KDR,KH.nb.w,mlvar=F)
# KDR_LISA.adj[14]
# xz=(KDR-mean(KDR))/sd(KDR)
# xz[14]*sum(KH.nb.m[14,]*xz)

#3
KDR_FDR=localmoran(KDR,KH.nb.w,p.adjust.method="fdr")
KH$TOWN[KDR_FDR[,4]>0 & KDR_FDR[,5]<0.05]
## [1] "左營區" "甲仙區" "杉林區"
#4
coords=coordinates(KH)
KH.db=dnearneigh(coords,0,5000)
KH.db.in=include.self(KH.db)
KH.db.w=nb2listw(KH.db.in)

DPP_G=as.vector(localG(KH$DPP,KH.db.w))
DPP_p=pnorm(DPP_G,lower.tail =F)
DPP_p.fdr=p.adjust(DPP_p,method = "fdr")
KH$TOWN[DPP_p.fdr<0.05]
## [1] "左營區" "苓雅區" "鳳山區"