Debian Codegraph @

R/maps.R

raw
1 #' @templateVar class map
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `map` object returned from [maps::map()].
5 #' @template param_unused_dots
6 #'
7 #' @evalRd return_tidy(
8 #' "term",
9 #' long = "Longitude.",
10 #' lat = "Latitude.",
11 #' .post = "Remaining columns give information on geographic attributes
12 #' and depend on the inputted map object. See ?maps::map for more information."
13 #' )
14 #'
15 #' @examplesIf rlang::is_installed(c("maps", "ggplot2"))
16 #'
17 #' # load libraries for models and data
18 #' library(maps)
19 #' library(ggplot2)
20 #'
21 #' ca <- map("county", "ca", plot = FALSE, fill = TRUE)
22 #'
23 #' tidy(ca)
24 #'
25 #' qplot(long, lat, data = ca, geom = "polygon", group = group)
26 #'
27 #' tx <- map("county", "texas", plot = FALSE, fill = TRUE)
28 #' tidy(tx)
29 #' qplot(long, lat,
30 #' data = tx, geom = "polygon", group = group,
31 #' colour = I("white")
32 #' )
33 #'
34 #' @export
35 #' @seealso [tidy()], [maps::map()]
36 #' @aliases maps_tidiers
37 tidy.map <- function(x, ...) {
38 df <- as.data.frame(x[c("x", "y")])
39 names(df) <- c("long", "lat")
40 df$group <- cumsum(is.na(df$long) & is.na(df$lat)) + 1
41 df$order <- 1:nrow(df)
42
43 names <- do.call("rbind", lapply(strsplit(x$names, "[:,]"), "[", 1:2))
44 df$region <- names[df$group, 1]
45 df$subregion <- names[df$group, 2]
46 as_tidy_tibble(df[stats::complete.cases(df$lat, df$long), ])
47 }