Skip to content

Instantly share code, notes, and snippets.

@ramhiser
Last active August 29, 2015 14:20
Show Gist options
  • Save ramhiser/2a7a3adfb0d8fbfbaa20 to your computer and use it in GitHub Desktop.
Save ramhiser/2a7a3adfb0d8fbfbaa20 to your computer and use it in GitHub Desktop.
Add NA row for each group in data frame
# Useful for drawing polygons with leaflet
# Polygons are stored in a `tbl_df` object with a mandatory `NA` row between each
# polygon so that `leaflet` knows to stop drawing between each polygon.
# Rather than magic, I found a slick way to do this via `dplyr::arrange`
# See: (http://stackoverflow.com/a/25267681/234233).
# Example using Iris data set:
df_na <- matrix(NA, nrow=nlevels(iris$Species), ncol=ncol(iris) - 1)
df_na <- tbl_df(as.data.frame(df_na))
colnames(df_na) <- setdiff(colnames(iris), "Species")
df_na$Species <- factor(levels(iris$Species))
bind_rows(df_na, iris) %>%
arrange(!is.na(Species), Species)
# Results look like:
#
# Source: local data frame [153 x 5]
#
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 NA NA NA NA setosa
# 2 5.1 3.5 1.4 0.2 setosa
# 3 4.9 3.0 1.4 0.2 setosa
# 4 4.7 3.2 1.3 0.2 setosa
# 5 4.6 3.1 1.5 0.2 setosa
# 6 5.0 3.6 1.4 0.2 setosa
# 7 5.4 3.9 1.7 0.4 setosa
# 8 4.6 3.4 1.4 0.3 setosa
# 9 5.0 3.4 1.5 0.2 setosa
# 10 4.4 2.9 1.4 0.2 setosa
# .. ... ... ... ... ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment