#2 Code en vrac : R Shiny – Mapping and Date Selection

In this new article from raspvor, we will see how we can create a Map showing a number of sales per postal codes. We will be able to select the starting and the ending date and see the corresponding map. This work was done with R Shiny.

This is the result we want to have :

R shiny mapping and date selection

You will see below the 3 R code which enable to have the result above.

1st R code : Mapping_OnlineSales.R

#################################################
#############Packages############################
#################################################
#install.packages("ggmap")
#install.packages("dplyr")
#install.packages("stringr")

#install.packages("maptools")
#install.packages("rgdal")
#install.packages("classInt")
#install.packages("RColorBrewer")

#load the library
library(ggmap)
library(RgoogleMaps)
library(dplyr)
library(stringr)

library(maptools)
library(rgdal)
library(classInt)
library(RColorBrewer)

#################################################
#############.Input##############################
#################################################
#Set up the path and read the data from the CSV File
myFolder <-  "C:/Users/Utilisateur_1/Desktop/Rproject/Mapping_OnlineSales"
myFile <- "Online_Data.csv"
path_myData = paste(myFolder,"/",myFile, sep ="")
myData = read.csv(path_myData, header = TRUE, sep = ",")

#Change the type of the column Date to ensure it is a date
myData[,1] = as.Date(myData[,1])
sapply(myData, class)

#################################################
############ Function ###########################
#################################################
#Function to filter myData by Date
filterDate <- function(x,y){myData[myData$Date >= x & myData$Date <= y,]}

2nd R code : server.R

#Launch code "Mapping_OnlineSales.R"
source("C:/Users/Utilisateur_1/Desktop/Rproject/Mapping_OnlineSales/Mapping_OnlineSales.R")

library(shiny)

function(input, output, session) {
  
  #Set up dateRangeText variable for verbatimTextOutput in ur.R
  output$dateRangeText <- renderText({
    paste("The selected period is :", 
          paste(as.character(input$dateRange), collapse = " a ")
    )
  })
  
  #################################################
  #############•Input##############################
  #################################################
 
  #Dowload the postal code shape of france from the url : https://www.data.gouv.fr/fr/datasets/fond-de-carte-des-codes-postaux/
  #Use it to produce our Map of France with all the Postal Code
  France <- reactive({
    readShapeSpatial("codes_postaux/codes_postaux_region.shp")
  })
  
  #Our code to create the map
  colcode <- reactive({
    
    #INPUT : Date selected with dateRangeInput (see ui.R)
    DATE1 <- as.Date(input$dateRange[1])
    DATE2 <- as.Date(input$dateRange[2])
    
    #We produce a new table with the date filtered
    #OnlineSales_CP <- filterDate(DATE1,DATE2)  
    
    #We calculate the frequency by Postal Code (in french CP = Code Postal)
    freq_OnlineSales <- data.frame(ftable(filterDate(DATE1,DATE2)$CP))
    colnames(freq_OnlineSales) <- c("CP", "Freq")
    
    #################################################
    #############Map creation###############
    #################################################
    
    #We create a table where ,for each Postal Code, we add the number of Sales
    m=match(France()$ID,freq_OnlineSales$CP)
    plotvar=freq_OnlineSales$Freq
    
    nclr=7
    plotclr=brewer.pal(nclr,"OrRd")[1:nclr] 
    
    plotvarFR = plotvar[m]
    
    #We put 0 if there was no sale (the value is currently NA)
    for (i in 1:length(plotvarFR)){
      if (is.na(plotvarFR[i])) {
        plotvarFR[i] = 0
      }
    }
    
    #We create the Intervals for the plot, each interval will have a color
    brk <- c(0,1,2,3,4,5,100)
    class=classIntervals(plotvarFR, length(brk)-1,style="fixed", fixedBreaks = brk, dataPrecision=1)
    return(findColours(class, plotclr))
  })
  
  #Set up the output to be plot in ur.R
  output$myPlot <- renderPlot({
    par(mar=c(1,1,1,1))
    plot(France(),col=colcode(),border=colcode())
    legend(26000, 6367308,legend=names(attr(colcode(),"table")), 
           fill=attr(colcode(), "palette"), cex=1, bty="n",
           title="# of Sales")
  })
}

3rd R code : ui.R

library(shiny)

fluidPage(
  #Title
  titlePanel("Choose your Dates"),
  
  #Selection of the Dates which will become our input (by using dateRangeInput)
  column(4, wellPanel(
    dateRangeInput('dateRange',
                   label = paste('Let s go!'),
                   start = Sys.Date() - 365, end = Sys.Date(),
                   max = Sys.Date(),
                   startview = 'year', language = 'fr', weekstart = 1
    )
  )),
  
  #Text to confirm the date selected
  column(7,verbatimTextOutput("dateRangeText")
  ),
  
  #Plot the Map
  mainPanel(
    plotOutput('myPlot'),
    height = "100%", width = "100%"
  )
)