Tuesday, May 18, 2010

Kern County Nearest Neighbor

Here is my attempt to replicate the Afghanistan in-class practice using census data for Kern County. For some reason, I was unable to merge demographic data with the shape-file. This means that I don't really have anything too exciting to share or reveal.

library(maptools)

library(spdep)

library(classInt)

library(RColorBrewer)


census <- readShapePoly("/Users/carrielevan/Documents/Geo299/ShapeFileHW/06029_Kern_County/tl_2009_06029_bg00/tl_2009_06029_bg00.shp" ,proj4string=CRS("+proj=longlat"))


#summarize new R object;

summary(census)


#view shapefile

plot(census)























coordinates(census)


#put centroids into a file and make it a data frame;

centers = coordinates(census)

centers = data.frame(centers)


#plot the coordinates

points(centers,col="blue",cex=1.2)



























#Adding Labels

text(centers,labels=rownames(centers),cex=1.5)
























#MEASURING SPACE: nearest neighbors & distance-based neighbors


kern.centers = coordinates(census)


#how many neighbors, k, are of interest? Why?

k=1


#determine the k nearest neighbors for each point in afghan.centers;

knn1 = knearneigh(kern.centers,k,longlat=T)


#create a neighbors list from the knn1 object;

kern.knn1 = knn2nb(knn1)


#map k-nearest neighbors;

plot(census)

plot(kern.knn1,kern.centers,col="blue",add=T)











#2 Nearest Neighbors

k=2

knn2 = knearneigh(kern.centers,k,longlat=T)

kern.knn2 = knn2nb(knn2)

plot(census)

plot(kern.knn2,kern.centers,col="green",add=T)











#3 Nearest Neighbors

k=3

knn3 = knearneigh(kern.centers,k,longlat=T)

kern.knn3 = knn2nb(knn3)

plot(census)

plot(kern.knn3,kern.centers,col="red",add=T)























k=4

knn4 = knearneigh(kern.centers,k,longlat=T)

kern.knn4 = knn2nb(knn4)

plot(census)

plot(kern.knn4,kern.centers,col="purple",add=T)


























k=5

knn5 = knearneigh(kern.centers,k,longlat=T)

kern.knn5 = knn2nb(knn5)

plot(census)

plot(kern.knn5,kern.centers,col="pink",add=T)


























##Neighbors based on distance in kilometers

d = .05

kern.dist.05 = dnearneigh(kern.centers,0,d,longlat=T)

plot(census)

plot(kern.dist.05,kern.centers,add=T,lwd=2,col="green")


























d = .1

kern.dist.1 = dnearneigh(kern.centers,0,d,longlat=T)

plot(census)

plot(kern.dist.1,kern.centers,add=T,lwd=2,col="blue")



























d = .25


#create a distance based neighbors object (kern.dist.25) with a .25km threshold;

kern.dist.25 = dnearneigh(kern.centers,0,d,longlat=T)


#map neighbors based on distance;

plot(census)

plot(kern.dist.25,kern.centers,add=T,lwd=2,col="red")


























#obtain summary report of afghan.dist.100 object

summary(kern.dist.25)







No comments:

Post a Comment

Followers