Skip to content

Instantly share code, notes, and snippets.

View ateucher's full-sized avatar

Andy Teucher ateucher

View GitHub Profile
@ateucher
ateucher / ggmap_sf.R
Last active June 15, 2018 16:48
ggmap_sf
#' Plot a ggmap object when you will be adding geom_sf() layers
#'
#' This is a wrapper around [ggmap::ggmap()], that transforms the bounding
#' box of the ggmap object to epsg:3857, which is what the underlying
#' data is in. This allows you to add `geom_sf()` layers with a crs
#' of epsg:3857 and have them line up properly.
#'
#' See [this stackoverflow question](https://stackoverflow.com/q/47749078/1736291)
#'
#'
library(sf)
library(dplyr)

url <- "https://data.cityofnewyork.us/api/geospatial/yfnk-k7r4?method=export&format=GeoJSON"

ny_data <- read_sf(url)

looks_numeric <- function(x) {
  # if already numeric or the sfc column, ignore
library(raster)
#> Loading required package: sp

# Make a tiny test raster, ensure one pixel is exactly 500:
x <- seq(0,1000, length.out = 9)
x
#> [1]    0  125  250  375  500  625  750  875 1000

rast &lt;- raster(matrix(x, ncol = 3))
@ateucher
ateucher / sf_empty.R
Last active May 28, 2018 23:13
Inconsistent behaviour with empty sf objects
library(sf)
# A geometry object with mixed multi and single polygons, some of which are empty
mixed_poly <- st_as_sfc(c("MULTIPOLYGON (((5.5 0, 7 0, 7 -0.5, 5.5 0)), ((6.6 1, 8 1, 8 1.5, 6.6 1)))",
"POLYGON ((5.5 0, 7 0, 7 -0.5, 5.5 0))",
"MULTIPOLYGON EMPTY",
"POLYGON EMPTY"
))
class(mixed_poly)
library(sf)
library(bcmaps)
library(transformr)
library(dplyr)
library(tweenr)
library(ggplot2)
library(gganimate)
bc_3005 <- bc_bound()
bc_4326 <- st_transform(bc_3005, 4326)
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, proj.4 5.0.0
library(rmapshaper)
library(geojsonio)
#> 
#> Attaching package: 'geojsonio'
#> The following object is masked from 'package:base':
#> 
#>     pretty
@ateucher
ateucher / snake_camel.R
Created March 22, 2018 21:15
Convert between snake_case and camelCase
camel_to_snake <- function(x, case = c("lower", "upper")) {
case <- match.arg(case)
case_fun <- switch(case, lower = tolower, upper = toupper)
case_fun(gsub("([a-z0-9])([A-Z]+)", "\\1_\\2", x))
}
snakeToCamel <- function(x) {
x <- tolower(x)
gsub("([a-z0-9]+)_([a-z0-9])", "\\1\\U\\2\\E", x, perl = TRUE)
}
## GOAL:
## re-create a figure similar to Fig. 2 in Wilson et al. (2018),
## Nature 554: 183-188. Available from:
## https://www.nature.com/articles/nature25479#s1
##
## combines a boxplot (or violin) with the raw data, by splitting each
## category location in two (box on left, raw data on right)
# initial set-up ----------------------------------------------------------
  • plumber (Jeff Allen)

  • python/reticulate

  • sf (Edzer)

  • modelling (Max Kuhn

  • tidyeval (Hadley

# I tried this but nothing plots:
library(ggplot2)
ggplot(diamonds, aes(x = carat, y = price, colour = cut))