Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Last active July 4, 2019 03:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelyportfolio/bf0ec45f0642a1a0f0ae3bed2485201e to your computer and use it in GitHub Desktop.
Save timelyportfolio/bf0ec45f0642a1a0f0ae3bed2485201e to your computer and use it in GitHub Desktop.
R sf simple features with quakes data, st_make_grid, dplyr, mapview zcol
library(sf)
library(dplyr)
library(mapview)
library(mapedit)
qk_mx <- data.matrix(quakes[,2:1])
qk_mp <- st_multipoint(qk_mx)
qk_sf <- st_sf(st_cast(st_sfc(qk_mp), "POINT"), quakes, crs=4326)
grd <- st_sf(geom=st_make_grid(qk_sf), crs=4326)
grd_mut <- grd %>%
# add id
mutate(id = 1:n()) %>%
# calculate
# index of quakes contained in grid rect
# number of quakes in grid rect
# mean mag of quakes in grid rect
mutate(
qk_contained = lapply(st_contains(st_sf(geom), qk_sf), identity),
n_quakes = sapply(qk_contained,length),
mean_mag = sapply(
qk_contained,
function(x) {
mean(qk_sf[x,]$mag)
}
)
) #%>%
# make n_quakes NA if 0
#mutate(
# n_quakes = ifelse(n_quakes==0, NA, n_quakes),
# mean_mag = ifelse(is.nan(mean_mag), 0, mean_mag)
#)
mapview(grd_mut, zcol="n_quakes", na.color="gray", legend=TRUE)
# as edzer highlights there is only na.color and not na.alpha
mapview(grd_mut, zcol="mean_mag", na.color="white", legend=TRUE)
@tim-salabim
Copy link

The mapview addLargeFeatures mode does not work properly in this case as the png state is cropped at the dateline. A long standing issue with leaflet/mapview. In fact, the very first reported issue on mapview is still open :-( r-spatial/mapview#6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment