Skip to content

Instantly share code, notes, and snippets.

@andrewbtran
Created August 7, 2016 00:06
Show Gist options
  • Select an option

  • Save andrewbtran/64abc11896e869a85993cf97c35e29cd to your computer and use it in GitHub Desktop.

Select an option

Save andrewbtran/64abc11896e869a85993cf97c35e29cd to your computer and use it in GitHub Desktop.
Analyzing points in a polygon in R
# Calculating points in a polygon
by_tract <- over(sp, towntracts_only)
# What just happened: Every point in the list now has a corresponding census tract
kable(head(by_tract, 5))
# Use dplyr to gather up and count how many instances of census tracts there are
require(dplyr)
by_tract <- by_tract %>%
group_by(GEOID10) %>%
summarise(total=n())
# Get rid of the census tracts with no data
by_tract <- by_tract[!is.na(by_tract$GEOID10),]
kable(head(by_tract,5))
# Rename the columns of this datframe so it can be joined to future data
colnames(by_tract) <- c("id", "total")
# Changing the GEOID number to character so it can be joined to future data
by_tract$id <- as.character(by_tract$id)
# Bring in a dataframe that has matches census tract ID numbers to town names
tracts2towns <- read.csv("data/tracts_to_towns.csv", stringsAsFactors=FALSE)
kable(head(tracts2towns, 5))
# Changing the column names so it can be joined to the by_tract dataframe
colnames(tracts2towns) <- c("id", "town_name")
# Changing the GEOID number to character so it can be joined to the by_tract dataframe
tracts2towns$id <- as.character(tracts2towns$id)
# Adding a 0 to the front of the GEOID string because it was originally left out when it was imported
tracts2towns$id <- paste0("0", tracts2towns$id)
# Bringing in a library to deal with strings
library(stringr)
# Eliminating leading and trailing white space just in case
tracts2towns$town_name <- str_trim(tracts2towns$town_name)
# Joining the by_tract dataframe to the tracts2towns dataframe
by_tract <- left_join(by_tract, tracts2towns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment