There and Back Again competition entry https://shiny.petras.space/commute/
rstats
rshiny
census
competition
leaflet
javascript
stats-nz

app.R 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. library(shiny)
  2. library(shinyjs)
  3. library(leaflet)
  4. library(rgdal)
  5. library(dplyr)
  6. library(leaflet.extras)
  7. library(shinyWidgets)
  8. source("leafletfunctions.R")
  9. source("extras.R")
  10. # work_travel <- read_csv("../travel-work.csv")
  11. load(file="datasets.RData")
  12. shpf <- readOGR(dsn="sa20025WGSfilcth")
  13. sa.in.dest <- shpf@data$SA22018_V1 %in% work_to$work_code
  14. sa.in.home <- shpf@data$SA22018_V1 %in% work_from$res_code
  15. transport.t <- c("Work at home", "Private car", "Company car",
  16. "Carpool", "Bus", "Train", "Bicycle", "Walk",
  17. "Ferry", "Other", "None")
  18. cols.labs <- c(transport.t[1:10], "Total")
  19. codelist <- shpf@data %>%
  20. mutate(sa2_code = as.numeric(as.character(SA22018_V1))) %>%
  21. select(sa2_code)
  22. startcols.res <- codelist %>% left_join(work_from, by = c("sa2_code" = "res_code"))
  23. startcols.res <- tencols[startcols.res$MAX]
  24. startcols.res <- ifelse(is.na(startcols.res), "#808080", startcols.res)
  25. startcols.work <- codelist %>% left_join(work_to, by = c("sa2_code" = "work_code"))
  26. startcols.work <- tencols[startcols.work$MAX]
  27. startcols.work <- ifelse(is.na(startcols.work), "#808080", startcols.work)
  28. hrstr <- "<hr style='border-top: 1px solid #000;'/>"
  29. # Define UI
  30. ui <- fluidPage(
  31. useShinyjs(),
  32. leafletjs,
  33. tags$style(type = "text/css", extracss),
  34. leafletOutput("map"),
  35. absolutePanel(top = 10, right = 10, id="mapcontrol",
  36. div(
  37. radioButtons("radioinout", label="Show commuters who",
  38. choiceNames = list(
  39. HTML("<p>Commute <b>from</b> selected area</p>"),
  40. HTML("<p>Commute <b>to</b> selected area</p>")),
  41. choiceValues = list(
  42. "res",
  43. "work"
  44. ),
  45. inline = FALSE),
  46. radioButtons("radiocolour",
  47. label = "Colour by",
  48. choiceNames = list(
  49. HTML("<p>Most common commute method</p>"),
  50. HTML("<p>Number of commuters</p>")
  51. ),
  52. choiceValues = list(
  53. "type",
  54. "number"
  55. ),
  56. inline = FALSE),
  57. div(id="locinfo",
  58. htmlOutput("lochtml")))),
  59. absolutePanel(top = 25, right = 10, id="control2",
  60. materialSwitch("controlswitch", value=TRUE, right=TRUE,
  61. inline=TRUE, status="info")),
  62. absolutePanel(bottom = 26, right = 10, id="loading",
  63. p("Loading...")),
  64. absolutePanel(bottom=26, right=10, left=10, top=10, id="infopanel",
  65. infotext),
  66. absolutePanel(bottom=10, left=10, id="infobuttoncontainer",
  67. prettyToggle("mapinfobutton", label_on = "Info",
  68. label_off = "Info", icon_on=icon("times"),
  69. icon_off = icon("info"),
  70. animation = "pulse",
  71. inline = TRUE,
  72. status_on = "danger",
  73. status_off = "info")
  74. )
  75. )
  76. # Define server logic
  77. server <- function(input, output) {
  78. sel.SA2.code <- reactiveVal(0)
  79. attribupdate <- FALSE
  80. output$map <- renderLeaflet({
  81. leaf <- leaflet(shpf, options = leafletOptions(minZoom = 3, maxZoom = 13)) %>%
  82. addPolygons(color="#000", opacity = 1, weight=1,
  83. fillColor = startcols.res,
  84. layerId = ~SA22018_V1,
  85. label = shpf@data$SA22018__1,
  86. fillOpacity = 1) %>%
  87. setView(174, -41, 6) %>%
  88. addResetMapButton() %>%
  89. addLegend(position = "topleft",
  90. colors = c(tencols, "#808080"),
  91. labels = transport.t, opacity = 1,
  92. title = "Commute method")
  93. shinyjs::hideElement(selector="#loading p", asis = TRUE,
  94. anim=TRUE, animType = "slide", time=10)
  95. leaf
  96. })
  97. updateMap <- function() {
  98. shinyjs::showElement(selector="#loading p", asis = TRUE,
  99. anim=TRUE, animType = "slide")
  100. selcode <- sel.SA2.code()
  101. selcode <- ifelse(is.na(selcode), 0, selcode)
  102. psel <- selcode %in% shpf@data$SA22018_V1
  103. if (input$radiocolour == "type") {
  104. if (input$radioinout == "work") {
  105. fcols <- startcols.work
  106. if (psel) {
  107. codvs <- work_simp %>% filter(work_code == selcode)
  108. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "res_code"))
  109. codvs <- tencols[codvs$MAX]
  110. fcols <- ifelse(is.na(codvs), "#808080", codvs)
  111. }
  112. } else {
  113. fcols <- startcols.res
  114. if (psel) {
  115. codvs <- work_simp %>% filter(res_code == selcode)
  116. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "work_code"))
  117. codvs <- tencols[codvs$MAX]
  118. fcols <- ifelse(is.na(codvs), "#808080", codvs)
  119. }
  120. }
  121. lp <- leafletProxy("map", data = shpf) %>%
  122. setShapeStyle(layerId = ~SA22018_V1, fillColor = fcols) %>%
  123. clearControls() %>%
  124. addLegend(position = "topleft",
  125. colors = c(tencols, "#808080"),
  126. labels = transport.t, opacity = 1,
  127. title = "Commute method"
  128. ) %>%
  129. clearGroup("hpoly")
  130. } else {
  131. if (input$radioinout == "work") {
  132. if (psel) {
  133. codvs <- work_simp %>% filter(work_code == selcode)
  134. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "res_code"))
  135. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  136. } else {
  137. codvs <- codelist %>%
  138. left_join(work_to, by = c("sa2_code" = "work_code"))
  139. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  140. }
  141. } else {
  142. if (psel) {
  143. codvs <- work_simp %>% filter(res_code == selcode)
  144. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "work_code"))
  145. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  146. } else {
  147. codvs <- codelist %>%
  148. left_join(work_from, by = c("sa2_code" = "res_code"))
  149. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  150. }
  151. }
  152. cvr <- range(cvals, na.rm = TRUE)
  153. binner <- colorBin(c("white", "red"), cvr, bins = 7, pretty = TRUE)
  154. lp <- leafletProxy("map", data = shpf) %>%
  155. setShapeStyle(layerId = ~SA22018_V1, fillColor = binner(cvals)) %>%
  156. clearControls() %>%
  157. addLegend(position = "topleft",
  158. pal = binner,
  159. values = cvals, opacity = 1,
  160. na.label = "None",
  161. title = "Number of commuters") %>%
  162. clearGroup("hpoly")
  163. }
  164. if (psel) {
  165. lp %>% addPolygons(group = "hpoly",
  166. weight = 4,
  167. data = shpf[which(shpf@data$SA22018_V1 == selcode),],
  168. color = "#000000",
  169. fill = FALSE, opacity = 1)
  170. }
  171. shinyjs::hideElement(selector="#loading p", asis=TRUE,
  172. anim=TRUE, animType = "slide",
  173. time = 1)
  174. }
  175. observeEvent(input$map_click, ignoreInit = TRUE, {
  176. cursel <- sel.SA2.code()
  177. p <- input$map_click
  178. pdat <- data.frame(Longitude = p$lng,
  179. Latitude =p$lat)
  180. coordinates(pdat) <- ~ Longitude + Latitude
  181. proj4string(pdat) <- proj4string(shpf)
  182. ppoly <- over(pdat, shpf)
  183. codetmp <- as.numeric(as.character(ppoly[1,"SA22018_V1"]))
  184. codetmp <- ifelse(is.na(codetmp), 0, codetmp)
  185. newsl <- ifelse(sel.SA2.code() == codetmp, 0, codetmp)
  186. if (newsl != cursel) {
  187. sel.SA2.code(newsl)
  188. updateMap()
  189. }
  190. })
  191. observeEvent(input$map_zoom, once=TRUE, {
  192. if (!attribupdate) {
  193. shinyjs::html(selector=".leaflet-control-attribution.leaflet-control",
  194. html = attribhtml)
  195. attribupdate <<- TRUE
  196. }
  197. })
  198. observeEvent(input$map_shape_mouseover, once=TRUE,{
  199. # Backup
  200. if (!attribupdate) {
  201. shinyjs::html(selector=".leaflet-control-attribution.leaflet-control",
  202. html = attribhtml)
  203. attribupdate <<- TRUE
  204. }
  205. })
  206. observeEvent(input$radioinout, ignoreInit = TRUE, {
  207. updateMap()
  208. })
  209. observeEvent(input$infobutton, {
  210. print(input$infobutton)
  211. })
  212. observeEvent(input$radiocolour, ignoreInit = TRUE, {
  213. updateMap()
  214. })
  215. observeEvent(input$controlswitch, ignoreInit = TRUE, {
  216. shinyjs::toggleElement("mapcontrol", anim=TRUE,
  217. time = 0.5)
  218. })
  219. observeEvent(input$mapinfobutton, ignoreInit = TRUE, {
  220. shinyjs::toggleElement("infopanel", anim=TRUE,
  221. time = 0.5)
  222. })
  223. output$lochtml <- renderUI({
  224. seled <- sel.SA2.code()
  225. seled <- ifelse(is.na(seled), 0, seled)
  226. if (!(seled %in% shpf@data$SA22018_V1)) {
  227. HTML(paste0(hrstr,
  228. "<p><em>No area selected</em></p>"))
  229. } else {
  230. namesel <- shpf@data$SA22018__1[shpf@data$SA22018_V1 == seled]
  231. if (input$radiocolour == "type") {
  232. str <- sprintf("<b>%s</b>", namesel)
  233. if (input$radioinout == "work") {
  234. str <- sprintf("<p>Commuting method of people who <b>work</b> in</p>
  235. <p><b><u>%s</u></b></p>", str)
  236. vals <- as.numeric(work_to[work_to$work_code == seled, 5:15])
  237. vals <- ifelse(is.na(vals), 0, vals)
  238. vals <- ifelse(vals < 0, "~0", as.character(vals))
  239. listi <- paste0(sprintf("<li>%s: %s</li>", cols.labs,
  240. vals),
  241. collapse="")
  242. str <- paste0(hrstr, str, "<ul>", listi, "</ul>")
  243. } else {
  244. str <- sprintf("<p>Commuting method of people who <b>live</b> in</p>
  245. <p><u>%s</u></p>", str)
  246. vals <- as.numeric(work_from[work_from$res_code == seled, 5:15])
  247. vals <- ifelse(is.na(vals), 0, vals)
  248. vals <- ifelse(vals < 0, "~0", as.character(vals))
  249. listi <- paste0(sprintf("<li>%s: %s</li>", cols.labs,
  250. vals),
  251. collapse="")
  252. str <- paste0(hrstr, str, "<ul>", listi, "</ul>")
  253. }
  254. HTML(str)
  255. } else {
  256. str <- hrstr
  257. if (input$radioinout == "work") {
  258. val <- as.numeric(work_to[work_to$work_code == seled, 15])
  259. val <- ifelse(is.na(val), 0, ifelse(val < 0, 0, val))
  260. str <- sprintf("%s<p>%d people commute <b>to</b></p>
  261. <p><b><u>%s</u></b></p>", str, val, namesel)
  262. if (val > 0) {
  263. subs <- work_simp %>% filter(work_code == seled) %>%
  264. arrange(desc(total)) %>% head(10)
  265. listi <- paste0(sprintf("<li>%s: %s</li>", subs$res_name,
  266. subs$total),
  267. collapse="")
  268. str <- sprintf("%s<p>Top areas to commute from<p>
  269. <ul>%s</ul>", str, listi)
  270. }
  271. } else {
  272. val <- as.numeric(work_from[work_from$res_code == seled, 15])
  273. val <- ifelse(is.na(val), 0, ifelse(val < 0, 0, val))
  274. str <- sprintf("%s<p>%d people commute <b>from</b></p>
  275. <p><b><u>%s</u></b></p>", str, val, namesel)
  276. if (val > 0) {
  277. subs <- work_simp %>% filter(res_code == seled) %>%
  278. arrange(desc(total)) %>% head(10)
  279. listi <- paste0(sprintf("<li>%s: %s</li>", subs$work_name,
  280. subs$total),
  281. collapse="")
  282. str <- sprintf("%s<p>Top areas to commute to<p>
  283. <ul>%s</ul>", str, listi)
  284. }
  285. }
  286. HTML(str)
  287. }
  288. }
  289. })
  290. }
  291. # Run the application
  292. shinyApp(ui = ui, server = server)