Skip to content

Instantly share code, notes, and snippets.

View smach's full-sized avatar

Sharon Machlis smach

View GitHub Profile

Keybase proof

I hereby claim:

  • I am smach on github.
  • I am sharon000 (https://keybase.io/sharon000) on keybase.
  • I have a public key whose fingerprint is C87F C261 72AE 1D42 1CCD 1F23 2C3F B45F 022F 6E5A

To claim this, I am signing this object:

# This function and helper functions create a Leaflet interactive map in R from a World Bank indicator. This code was created by Kyle E. Walker, director of the Center for Urban Studies at Texas Christian University and (very) slightly modified by Sharon Machlis. See Walker's kwgeo package at https://github.com/walkerke/kwgeo/ for more info. Any errors are most certainly Sharon's.
if (!require("WDI")) install.packages("WDI")
if (!require("rgdal")) install.packages("rgdal")
if (!require("sp")) install.packages("sp")
if (!require("leaflet")) install.packages("leaflet")
if (!require("httr")) install.packages("httr")
if (!require("maptools")) install.packages("maptools")
---
title: ''
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
mydata <- read.csv("https://gist.githubusercontent.com/smach/9cc166277488d2499e208d2076ff26c3/raw/e2f596ce6a134657e4daa73550510f6fb949890b/MAEarlyVotingData.csv", stringsAsFactors = FALSE)
mydata <- subset(mydata, RegisteredVoters >= 30000)
We can make this file beautiful and searchable if this error is corrected: Unclosed quoted field in line 5.
"Community","RegisteredVoters","Democrat","Republican","GreenRainbow","UnitedIndependent","Unenrolled","citytown","State","StateFIPS","PlaceFIPS","PlaceName","PlaceType","Status","County","Place","TotalHours","TotalEveningHours","SaturdayHours","SundayHours","TotalAMHours","NumLocations","ALAND_SQMI","VotersPerTotalHours","SqMilesPerLocation","VotersPerLocation","TotalNonBusiness"
"BOSTON",413670,217198,26198,607,2497,165823,"boston","MA",25,7000,"Boston city","County Subdivision","F","Suffolk County","Boston",101,10,6,0,0,28,48.366,4096,2,14774,16
"WORCESTER",104464,44656,8583,197,1076,49487,"worcester","MA",25,82000,"Worcester city","County Subdivision","F","Worcester County","Worcester",115.5,11,9,6,0,5,37.371,904,7,20893,26
"SPRINGFIELD",103923,53514,7957,122,626,41308,"springfield","MA",25,67000,"Springfield city","County Subdivision","F","Hampden County","Springfield",107,4,8,0,1,10,31.865,971,3,10392,13
"CAMBRIDGE",71351,40059,2760,222,283,27770,"cambridge","MA",25,11000,"Cambridge city","County Subdiv
@smach
smach / findwinner.R
Last active March 1, 2016 01:31
R function to find top vote-getter in a csv or Excel election results file. Requires rio package, and results file with candidate results in adjoining columns. findwinner function arguments: filename (string), datacolstart (number of data column where results data starts; 2 for column B in Excel, for example), datacolstop (number of the last dat…
function (filename, datacolstart, datacolstop, exportcsv = TRUE)
{
if (!require("rio"))
install.packages("rio")
data <- rio::import(filename)
for(i in 1:nrow(data)){
ranks <- rank(data[i,2:7])
maxrank <- as.numeric(max(ranks))
winners <- names(ranks[ranks==maxrank])
data$Winners[i] <- paste(winners, collapse = ", ")
# Example from R Graphics Cookbook by Winston Chang
# Install gcookbook package with
# install.packages("gcookbook")
# Bars have black outline while legend has outline + diagonal strike-through
library(gcookbook)
upc <- subset(uspopchange, rank(Change)>=40)
ggplot(upc, aes(x=reorder(Abb, Change), y=Change, fill=Region)) +
geom_bar(stat="identity", colour="black") +
library(readxl)
library(dplyr)
library(reshape2)
mydata <- read_excel("data/CaptainMelTournament2013.xls", sheet=1)
# Registration column is showing up, get rid of that. And note I removed the spaces from some column names to make them R friendly.
mydata <- mydata[,-1]
# reshape the data from wide to long
mydata_long <- melt(mydata, c("CheckinNumber", "FullName", "FirstName", "LastName", "Division"), variable.name = "Category", value.name = "Length")
generateTableCode <- function(mydata, headline="", caption="", sortable=TRUE, searchable=TRUE){
header_numstyle <- paste("<style>","div.table-wrapper table td.cwnumcol {","text-align: right;", "}", "</style>", sep="\n")
header_searchbox <- paste(
"<script type=\"text/javascript\">",
"$( document ).ready(function() {",
"var $rows = $('#cwsearchabletable tbody tr');",
"$('#cwtablesearchbox').keyup(function() {",
" var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();",
"$rows.show().filter(function() {",
" var text = $(this).text().replace(/\\s+/g, ' ').toLowerCase();",
@smach
smach / gist:1660f6cf3d8a68440024
Last active August 29, 2015 14:16
atlantawx.R
url <- "http://forecast.weather.gov/MapClick.php?lat=33.74899931200048&lon=-84.38797796399967&site=all&smap=1#.VPUbWfnF9EI"
library(rvest)
html <- html(url)
forecasthtml <- html_nodes(html, ".row-forecast")
forecast <- html_text(forecasthtml)
# Note: to deal with the lack of spaces now between Today, Tonight, etc. and the start of the forecasts, I added
forecast_formatted <- gsub("day([A-Z])", "day \\1", forecast)
forecast_formatted <- gsub("Night([A-Z])", "Night \\1", forecast_formatted)
forecast_formatted <- gsub("Tonight([A-Z])", "Tonight \\1", forecast_formatted)
forecast_formatted <- gsub("Afternoon([A-Z])", "Afternoon \\1", forecast_formatted)
@smach
smach / corrviz.R
Created February 28, 2015 20:48
Useful data visualization of a correlation matrix, code from the R Graphics Cookbook by Winston Chang
# Function takes a correlation matrix from the cor() function and outputs a visualization.
# The corrplot package must be installed.
# This code comes from the R Graphics Cookbook by Winston Chang
corrviz <- function(mycorrmatrix){
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot::corrplot(mycorrmatrix, method="shade", shade.col=NA, tl.col="black", tl.srt=45, col=col(200), addCoef.col="black")
}