Using File Uploaded in Rshiny as Data for R

Building a Shiny app to upload and visualize spatio-temporal data

In this chapter we evidence how to build a Shiny web application to upload and visualize spatio-temporal data (Chang et al. 2021). The app allows to upload a shapefile with a map of a region, and a CSV file with the number of affliction cases and population in each of the areas in which the region is divided. The app includes a diversity of elements for interactive data visualization such as a map built with leaflet (Cheng, Karambelkar, and Xie 2021), a table built with DT (Xie, Cheng, and Tan 2021), and a time plot congenital with dygraphs (Vanderkam et al. 2018). The app also allows interactivity by giving the user the possibility to select specific information to be shown. To build the app, nosotros utilize data of the number of lung cancer cases and population in the 88 counties of Ohio, USA, from 1968 to 1988 (Figure 15.1).

Snapshot of the Shiny app to upload and visualize spatio-temporal data.

Effigy 15.1: Snapshot of the Shiny app to upload and visualize spatio-temporal data.

Shiny

Shiny is a spider web awarding framework for R that enables to build interactive web applications. Chapter 13 provides an introduction to Shiny and examples, and hither we review its basic components. A Shiny app can be built by creating a directory (called, for example, appdir) that contains an R file (called, for instance, app.R) with three components:

  • a user interface object (ui) which controls the layout and appearance of the app,
  • a server() function with the instructions to build the objects displayed in the ui, and
  • a call to shinyApp() that creates the app from the ui/server pair.

Shiny apps contain input and output objects. Inputs allow users interact with the app by modifying their values. Outputs are objects that are shown in the app. Outputs are reactive if they are built using input values. The following code shows the content of a generic app.R file.

                                                # load the shiny package                                                  library(shiny)                                                  # define user interface object                                ui                  <-                  fluidPage(                                  *                  Input(inputId =                  myinput,                  label =                  mylabel, ...)                                  *                  Output(outputId =                  myoutput, ...)                )                                                  # define server() function                                server                  <-                  function(input, output){                                  output$myoutput                  <-                  render*({                                  # code to build the output.                                                  # If it uses an input value (input$myinput),                                                  # the output will exist rebuilt whenever                                                  # the input value changes                                                  })}                                                  # telephone call to shinyApp() which returns the Shiny app                                                  shinyApp(ui =                  ui,                  server =                  server)                          

The app.R file is saved inside a directory called, for example, appdir. Then, the app can exist launched by typing runApp("appdir_path") where appdir_path is the path of the directory that contains app.R, or past clicking the Run button of RStudio.

Setup

To build the Shiny app of this example, we need to download the folder appdir from the book webpage and save it in our computer. This folder contains the following subfolders:

  • data which contains a file called data.csv with the data of lung cancer in Ohio, and a folder called fe_2007_39_county with the shapefile of Ohio, and
  • www with an image of a Shiny logo called imageShiny.png.

Structure of app.R

We start creating the Shiny app by writing a file called app.R with the minimum lawmaking needed to create a Shiny app:

We save this file with the proper name app.R inside a directory called appdir. Then, we can launch the app past clicking the Run App button at the top of the RStudio editor or by executing runApp("appdir_path") where appdir_path is the path of the directory that contains the app.R file. The Shiny app created has a blank user interface. In the following sections, nosotros include the elements and functionality we wish to accept in the Shiny app.

Layout

We build a user interface with a sidebar layout. This layout includes a title panel, a sidebar console for inputs on the left, and a primary panel for outputs on the right. The elements of the user interface are placed within the fluidPage() function and this permits the app to adjust automatically to the dimensions of the browser window. The title of the app is added with titlePanel(). And so we write sidebarLayout() to create a sidebar layout with input and output definitions. sidebarLayout() takes the arguments sidebarPanel() and mainPanel(). sidebarPanel() creates a a sidebar panel for inputs on the left. mainPanel() creates a main panel for displaying outputs on the right.

We can add content to the app by passing it every bit an statement to titlePanel(), sidebarPanel(), and mainPanel(). Here we have added texts with the description of the panels. Note that to include multiple elements in the same panel, we demand to separate them with commas.

HTML content

Here we add together a title, an image and a website link to the app. First we add the championship "Spatial app" to titlePanel(). We desire to show this title in blue and so we utilize p() to create a paragraph with text and set the style to the #3474A7 color.

                                                titlePanel(p("Spatial app",                  style =                  "colour:#3474A7")),                          

Then nosotros add an image with the img() function. The images that we wish to include in the app must be in a folder named www in the same directory as the app.R file. Nosotros employ the image called imageShiny.png and put it in the sidebarPanel() past using the following education.

                                                sidebarPanel(img(src =                  "imageShiny.png",                                  width =                  "70px",                  meridian =                  "70px")),                          

Here src denotes the source of the paradigm, and meridian and width are the image height and width in pixels, respectively. We also add text with a link referencing the Shiny website.

                                                p("Fabricated with",                  a("Shiny",                                  href =                  "http://shiny.rstudio.com"),                  "."),                          

Note that in sidebarPanel() nosotros need to write the office to generate the website link and the function to include the image separated with a comma.

                                                sidebarPanel(                                  p("Made with",                  a("Shiny",                                  href =                  "http://shiny.rstudio.com"),                  "."),                                  img(src =                  "imageShiny.png",                                  width =                  "70px",                  top =                  "70px")),                          

Below is the content of app.R nosotros take until now. A snapshot of the Shiny app is shown in Figure fifteen.two.

                              library                (                shiny                )                # ui object                ui                <-                fluidPage                (                titlePanel                (                p                (                "Spatial app", style                =                "color:#3474A7"                )                ),                sidebarLayout                (                sidebarPanel                (                p                (                "Made with",                a                (                "Shiny",         href                =                "http://shiny.rstudio.com"                ),                "."                ),                img                (                src                =                "imageShiny.png",         width                =                "70px", height                =                "70px"                )                ),                mainPanel                (                "main panel for outputs"                )                )                )                # server()                server                <-                function                (                input,                output                )                {                }                # shinyApp()                shinyApp                (ui                =                ui, server                =                server                )                          

Snapshot of the Shiny app after including a title, an image and a website link.

FIGURE xv.two: Snapshot of the Shiny app after including a title, an prototype and a website link.

Read data

Now we import the data we want to show in the app. The information is in the binder called data in the appdir directory. To read the CSV file data.csv, we use the read.csv() function, and to read the shapefile of Ohio that is in the folder fe_2007_39_county, we use the readOGR() function of the rgdal parcel.

We simply need to read the data once then we write this code at the beginning of app.R outside the server() function. By doing this, the code is not unnecessarily run more than once and the performance of the app is not decreased.

Calculation outputs

Now nosotros prove the data in the Shiny app by including several outputs for interactive visualization. Specifically, we include HTML widgets created with JavaScript libraries and embedded in Shiny past using the htmlwidgets package (Vaidyanathan et al. 2021). The outputs are created using the following packages:

  • DT to brandish the data in an interactive table,
  • dygraphs to display a time plot with the data, and
  • leaflet to create an interactive map.

Outputs are added in the app past including in ui an *Output() role for the output, and adding in server() a return*() office to the output that specifies how to build the output. For example, to add a plot, nosotros write in the ui plotOutput() and in server() renderPlot().

Table using DT

We prove the data in data with an interactive table using the DT package. In ui we apply DTOutput(), and in server() we use renderDT().

Time plot using dygraphs

We bear witness a time plot with the data with the dygraphs package. In ui we use dygraphOutput(), and in server() nosotros use renderDygraph(). dygraphs plots an extensible time series object xts. We can create this type of object using the xts() role of the xts package (Ryan and Ulrich 2020) specifying the values and the dates. The dates in data are the years of column twelvemonth. For now we choose to plot the values of the variable cases of data.

Nosotros need to construct a xts object for each county then put them together in an object called dataxts. For each of the counties, we filter the information of the county and assign information technology to datacounty. Then we construct a xts object with values datacounty$cases and dates as.Date(paste0(data$year, "-01-01")). So we assign the name of the counties to each xts (colnames(dataxts) <- counties) and then county names can be shown in the fable.

                                  dataxts                  <-                  Zippo                  counties                  <-                  unique                  (                  data                  $                  county                  )                  for                  (                  l                  in                  1                  :                  length                  (                  counties                  )                  )                  {                  datacounty                  <-                  data                  [                  data                  $                  county                  ==                  counties                  [                  l                  ],                  ]                  dd                  <-                  xts                  (                  datacounty                  [,                  "cases"                  ],                  every bit.Date                  (                  paste0                  (                  datacounty                  $                  year,                  "-01-01"                  )                  )                  )                  dataxts                  <-                  cbind                  (                  dataxts,                  dd                  )                  }                  colnames                  (                  dataxts                  )                  <-                  counties                              

Finally, nosotros plot dataxts with dygraph(), and use dyHighlight() to allow mouse-over highlighting.

                                  dygraph                  (                  dataxts                  )                  %>%                  dyHighlight                  (highlightSeriesBackgroundAlpha                  =                  0.2                  )                              

We customize the fable so that just the name of the highlighted series is shown. To do this, one option is to write a css file with the instructions and pass the css file to the dyCSS() office. Alternatively, we can set the css directly in the code as follows:

                                  dygraph                  (                  dataxts                  )                  %>%                  dyHighlight                  (highlightSeriesBackgroundAlpha                  =                  0.ii                  )                  ->                  d1                  d1                  $                  x                  $                  css                  <-                  " .dygraph-legend > span {brandish:none;} .dygraph-fable > span.highlight { display: inline; } "                  d1                              

The consummate lawmaking to build the dygraphs object is the following:

                                  library                  (                  dygraphs                  )                  library                  (                  xts                  )                  # in ui                  dygraphOutput                  (outputId                  =                  "timetrend"                  )                  # in server()                  output                  $                  timetrend                  <-                  renderDygraph                  (                  {                  dataxts                  <-                  NULL                  counties                  <-                  unique                  (                  data                  $                  county                  )                  for                  (                  fifty                  in                  1                  :                  length                  (                  counties                  )                  )                  {                  datacounty                  <-                  information                  [                  information                  $                  canton                  ==                  counties                  [                  50                  ],                  ]                  dd                  <-                  xts                  (                  datacounty                  [,                  "cases"                  ],                  as.Date                  (                  paste0                  (                  datacounty                  $                  yr,                  "-01-01"                  )                  )                  )                  dataxts                  <-                  cbind                  (                  dataxts,                  dd                  )                  }                  colnames                  (                  dataxts                  )                  <-                  counties                  dygraph                  (                  dataxts                  )                  %>%                  dyHighlight                  (highlightSeriesBackgroundAlpha                  =                  0.2                  )                  ->                  d1                  d1                  $                  ten                  $                  css                  <-                  "  .dygraph-fable > span {display:none;}  .dygraph-fable > span.highlight { display: inline; }  "                  d1                  }                  )                              

Map using leaflet

We utilize the leaflet package to build an interactive map. In ui we utilize leafletOutput(), and in server() we apply renderLeaflet(). Inside renderLeaflet() nosotros write the instructions to return a leaflet map. First, we demand to add the data to the shapefile so the values can be plotted in a map. For at present we choose to plot the values of the variable in 1980. We create a dataset called datafiltered with the data corresponding to that yr. And so nosotros add datafiltered to map@data in an order such that the counties in the information friction match the counties in the map.

                                  datafiltered                  <-                  data                  [                  which                  (                  data                  $                  year                  ==                  1980                  ),                  ]                  # this returns positions of map@data$NAME in datafiltered$county                  ordercounties                  <-                  match                  (                  map                  @                  information                  $                  NAME,                  datafiltered                  $                  county                  )                  map                  @                  data                  <-                  datafiltered                  [                  ordercounties,                  ]                              

We create the leaflet map with the leaflet() function, create a color palette with colorBin(), and add a legend with addLegend(). For now nosotros choose to plot the values of variable cases. We also add labels with the area names and values that are displayed when the mouse is over the map.

                                  library                  (                  leaflet                  )                  # in ui                  leafletOutput                  (outputId                  =                  "map"                  )                  # in server()                  output                  $                  map                  <-                  renderLeaflet                  (                  {                  # add together data to map                  datafiltered                  <-                  data                  [                  which                  (                  data                  $                  yr                  ==                  1980                  ),                  ]                  ordercounties                  <-                  match                  (                  map                  @                  information                  $                  NAME,                  datafiltered                  $                  canton                  )                  map                  @                  data                  <-                  datafiltered                  [                  ordercounties,                  ]                  # create leaflet                  pal                  <-                  colorBin                  (                  "YlOrRd", domain                  =                  map                  $                  cases, bins                  =                  7                  )                  labels                  <-                  sprintf                  (                  "%s: %g",                  map                  $                  county,                  map                  $                  cases                  )                  %>%                  lapply                  (                  htmltools                  ::                  HTML                  )                  50                  <-                  leaflet                  (                  map                  )                  %>%                  addTiles                  (                  )                  %>%                  addPolygons                  (                  fillColor                  =                  ~                  pal                  (                  cases                  ),       color                  =                  "white",       dashArray                  =                  "3",       fillOpacity                  =                  0.7,       label                  =                  labels                  )                  %>%                  leaflet                  ::                  addLegend                  (                  pal                  =                  pal, values                  =                  ~                  cases,       opacity                  =                  0.7, title                  =                  NULL                  )                  }                  )                              

Below is the content of app.R we accept until now. A snapshot of the Shiny app is shown in Figure 15.three.

                                  library                  (                  shiny                  )                  library                  (                  rgdal                  )                  library                  (                  DT                  )                  library                  (                  dygraphs                  )                  library                  (                  xts                  )                  library                  (                  leaflet                  )                  data                  <-                  read.csv                  (                  "information/data.csv"                  )                  map                  <-                  readOGR                  (                  "data/fe_2007_39_county/fe_2007_39_county.shp"                  )                  # ui object                  ui                  <-                  fluidPage                  (                  titlePanel                  (                  p                  (                  "Spatial app", way                  =                  "color:#3474A7"                  )                  ),                  sidebarLayout                  (                  sidebarPanel                  (                  p                  (                  "Made with",                  a                  (                  "Shiny",         href                  =                  "http://shiny.rstudio.com"                  ),                  "."                  ),                  img                  (                  src                  =                  "imageShiny.png",         width                  =                  "70px", height                  =                  "70px"                  )                  ),                  mainPanel                  (                  leafletOutput                  (outputId                  =                  "map"                  ),                  dygraphOutput                  (outputId                  =                  "timetrend"                  ),                  DTOutput                  (outputId                  =                  "table"                  )                  )                  )                  )                  # server()                  server                  <-                  function                  (                  input,                  output                  )                  {                  output                  $                  tabular array                  <-                  renderDT                  (                  data                  )                  output                  $                  timetrend                  <-                  renderDygraph                  (                  {                  dataxts                  <-                  NULL                  counties                  <-                  unique                  (                  information                  $                  county                  )                  for                  (                  l                  in                  1                  :                  length                  (                  counties                  )                  )                  {                  datacounty                  <-                  information                  [                  data                  $                  county                  ==                  counties                  [                  l                  ],                  ]                  dd                  <-                  xts                  (                  datacounty                  [,                  "cases"                  ],                  as.Date                  (                  paste0                  (                  datacounty                  $                  yr,                  "-01-01"                  )                  )                  )                  dataxts                  <-                  cbind                  (                  dataxts,                  dd                  )                  }                  colnames                  (                  dataxts                  )                  <-                  counties                  dygraph                  (                  dataxts                  )                  %>%                  dyHighlight                  (highlightSeriesBackgroundAlpha                  =                  0.2                  )                  ->                  d1                  d1                  $                  x                  $                  css                  <-                  "  .dygraph-legend > bridge {display:none;}  .dygraph-legend > span.highlight { brandish: inline; }  "                  d1                  }                  )                  output                  $                  map                  <-                  renderLeaflet                  (                  {                  # Add data to map                  datafiltered                  <-                  information                  [                  which                  (                  information                  $                  year                  ==                  1980                  ),                  ]                  ordercounties                  <-                  match                  (                  map                  @                  data                  $                  NAME,                  datafiltered                  $                  county                  )                  map                  @                  data                  <-                  datafiltered                  [                  ordercounties,                  ]                  # Create leaflet                  pal                  <-                  colorBin                  (                  "YlOrRd", domain                  =                  map                  $                  cases, bins                  =                  seven                  )                  labels                  <-                  sprintf                  (                  "%s: %m",                  map                  $                  canton,                  map                  $                  cases                  )                  %>%                  lapply                  (                  htmltools                  ::                  HTML                  )                  50                  <-                  leaflet                  (                  map                  )                  %>%                  addTiles                  (                  )                  %>%                  addPolygons                  (                  fillColor                  =                  ~                  pal                  (                  cases                  ),         color                  =                  "white",         dashArray                  =                  "3",         fillOpacity                  =                  0.7,         label                  =                  labels                  )                  %>%                  leaflet                  ::                  addLegend                  (                  pal                  =                  pal, values                  =                  ~                  cases,         opacity                  =                  0.7, title                  =                  Zippo                  )                  }                  )                  }                  # shinyApp()                  shinyApp                  (ui                  =                  ui, server                  =                  server                  )                              

Snapshot of the Shiny app after including the map, the time plot, and the table.

Effigy fifteen.3: Snapshot of the Shiny app after including the map, the time plot, and the table.

Adding reactivity

At present we add functionality that enables the user to select a specific variable and twelvemonth to be shown. To be able to select a variable, we include an input of a menu containing all the possible variables. Then, when the user selects a particular variable, the map and the fourth dimension plot volition exist rebuilt. To add an input in a Shiny app, nosotros need to place an input part *Input() in the ui object. Each input function requires several arguments. The showtime 2 are inputId, an id necessary to access the input value, and label which is the text that appears side by side to the input in the app. We create the input with the menu that contains the possible choices for the variable as follows.

                              # in ui                selectInput                (                inputId                =                "variableselected",   label                =                "Select variable",   choices                =                c                (                "cases",                "population"                )                )                          

In this input, the id is variableselected, label is "Select variable" and choices contains the variables "cases" and "population". The value of this input tin can be accessed with input$variableselected. Nosotros create reactivity by including the value of the input (input$variableselected) in the render*() expressions in server() that build the outputs. Thus, when we select a different variable in the menu, all the outputs that depend on the input volition be rebuilt using the updated input value.

Similarly, we add a menu with id yearselected and with choices equal to all possible years so we can select the year we want to run across. When we select a year, the input value input$yearselected changes and all the outputs that depend on it volition be rebuilt using the new input value.

                              # in ui                selectInput                (                inputId                =                "yearselected",   label                =                "Select year",   choices                =                1968                :                1988                )                          

Reactivity in dygraphs

In this department we modify the dygraphs time plot and the leaflet map so that they are congenital with the input values input$variableselected and input$yearselected. Nosotros modify renderDygraph() by writing datacounty[, input$variableselected] instead of datacounty[, "cases"].

                                  # in server()                  output                  $                  timetrend                  <-                  renderDygraph                  (                  {                  dataxts                  <-                  Nada                  counties                  <-                  unique                  (                  data                  $                  county                  )                  for                  (                  l                  in                  ane                  :                  length                  (                  counties                  )                  )                  {                  datacounty                  <-                  data                  [                  data                  $                  county                  ==                  counties                  [                  50                  ],                  ]                  # Modify "cases" by input$variableselected                  dd                  <-                  xts                  (                  datacounty                  [,                  input                  $                  variableselected                  ],                  equally.Date                  (                  paste0                  (                  datacounty                  $                  yr,                  "-01-01"                  )                  )                  )                  dataxts                  <-                  cbind                  (                  dataxts,                  dd                  )                  }                  ...                  }                  )                              

Reactivity in leaflet

We also alter renderLeaflet() by selecting information respective to year input$yearselected and plot variable input$variableselected instead of variable cases. We create a new cavalcade in map chosen variableplot with the values of variable input$variableselected and plot the map with the values in variableplot. In leaflet() we modify colorBin(), addPolygons(), addLegend() and labels to show variableplot instead of variable cases.

                                  output                  $                  map                  <-                  renderLeaflet                  (                  {                  # Add data to map                  # Alter 1980 by input$yearselected                  datafiltered                  <-                  data                  [                  which                  (                  information                  $                  twelvemonth                  ==                  input                  $                  yearselected                  ),                  ]                  ordercounties                  <-                  match                  (                  map                  @                  data                  $                  NAME,                  datafiltered                  $                  county                  )                  map                  @                  data                  <-                  datafiltered                  [                  ordercounties,                  ]                  # Create variableplot                  # ADD this to create variableplot                  map                  $                  variableplot                  <-                  as.numeric                  (                  map                  @                  data                  [,                  input                  $                  variableselected                  ]                  )                  # Create leaflet                  # Alter map$cases past map$variableplot                  pal                  <-                  colorBin                  (                  "YlOrRd", domain                  =                  map                  $                  variableplot, bins                  =                  seven                  )                  # CHANGE map$cases by map$variableplot                  labels                  <-                  sprintf                  (                  "%s: %g",                  map                  $                  canton,                  map                  $                  variableplot                  )                  %>%                  lapply                  (                  htmltools                  ::                  HTML                  )                  # Alter cases by variableplot                  l                  <-                  leaflet                  (                  map                  )                  %>%                  addTiles                  (                  )                  %>%                  addPolygons                  (                  fillColor                  =                  ~                  pal                  (                  variableplot                  ),       color                  =                  "white",       dashArray                  =                  "3",       fillOpacity                  =                  0.7,       label                  =                  labels                  )                  %>%                  # Change cases past variableplot                  leaflet                  ::                  addLegend                  (                  pal                  =                  pal, values                  =                  ~                  variableplot,       opacity                  =                  0.7, title                  =                  NULL                  )                  }                  )                              

Note that a better way to modify an existing leaflet map is using the leafletProxy() function. Details on how to utilise this function are given in the RStudio website. The content of the app.R file is shown below and a snapshot of the Shiny app is shown in Effigy 15.4.

                                  library                  (                  shiny                  )                  library                  (                  rgdal                  )                  library                  (                  DT                  )                  library                  (                  dygraphs                  )                  library                  (                  xts                  )                  library                  (                  leaflet                  )                  data                  <-                  read.csv                  (                  "data/data.csv"                  )                  map                  <-                  readOGR                  (                  "data/fe_2007_39_county/fe_2007_39_county.shp"                  )                  # ui object                  ui                  <-                  fluidPage                  (                  titlePanel                  (                  p                  (                  "Spatial app", style                  =                  "color:#3474A7"                  )                  ),                  sidebarLayout                  (                  sidebarPanel                  (                  selectInput                  (                  inputId                  =                  "variableselected",         label                  =                  "Select variable",         choices                  =                  c                  (                  "cases",                  "population"                  )                  ),                  selectInput                  (                  inputId                  =                  "yearselected",         label                  =                  "Select year",         choices                  =                  1968                  :                  1988                  ),                  p                  (                  "Made with",                  a                  (                  "Shiny",         href                  =                  "http://shiny.rstudio.com"                  ),                  "."                  ),                  img                  (                  src                  =                  "imageShiny.png",         width                  =                  "70px", height                  =                  "70px"                  )                  ),                  mainPanel                  (                  leafletOutput                  (outputId                  =                  "map"                  ),                  dygraphOutput                  (outputId                  =                  "timetrend"                  ),                  DTOutput                  (outputId                  =                  "table"                  )                  )                  )                  )                  # server()                  server                  <-                  office                  (                  input,                  output                  )                  {                  output                  $                  table                  <-                  renderDT                  (                  data                  )                  output                  $                  timetrend                  <-                  renderDygraph                  (                  {                  dataxts                  <-                  NULL                  counties                  <-                  unique                  (                  data                  $                  canton                  )                  for                  (                  50                  in                  1                  :                  length                  (                  counties                  )                  )                  {                  datacounty                  <-                  information                  [                  data                  $                  county                  ==                  counties                  [                  50                  ],                  ]                  dd                  <-                  xts                  (                  datacounty                  [,                  input                  $                  variableselected                  ],                  equally.Date                  (                  paste0                  (                  datacounty                  $                  twelvemonth,                  "-01-01"                  )                  )                  )                  dataxts                  <-                  cbind                  (                  dataxts,                  dd                  )                  }                  colnames                  (                  dataxts                  )                  <-                  counties                  dygraph                  (                  dataxts                  )                  %>%                  dyHighlight                  (highlightSeriesBackgroundAlpha                  =                  0.2                  )                  ->                  d1                  d1                  $                  x                  $                  css                  <-                  "  .dygraph-legend > span {display:none;}  .dygraph-legend > bridge.highlight { display: inline; }  "                  d1                  }                  )                  output                  $                  map                  <-                  renderLeaflet                  (                  {                  # Add data to map                  # CHANGE 1980 by input$yearselected                  datafiltered                  <-                  data                  [                  which                  (                  data                  $                  yr                  ==                  input                  $                  yearselected                  ),                  ]                  ordercounties                  <-                  match                  (                  map                  @                  data                  $                  Proper noun,                  datafiltered                  $                  county                  )                  map                  @                  information                  <-                  datafiltered                  [                  ordercounties,                  ]                  # Create variableplot                  # Add this to create variableplot                  map                  $                  variableplot                  <-                  as.numeric                  (                  map                  @                  data                  [,                  input                  $                  variableselected                  ]                  )                  # Create leaflet                  # Modify map$cases by map$variableplot                  pal                  <-                  colorBin                  (                  "YlOrRd", domain                  =                  map                  $                  variableplot, bins                  =                  7                  )                  # CHANGE map$cases by map$variableplot                  labels                  <-                  sprintf                  (                  "%s: %1000",                  map                  $                  canton,                  map                  $                  variableplot                  )                  %>%                  lapply                  (                  htmltools                  ::                  HTML                  )                  # CHANGE cases by variableplot                  l                  <-                  leaflet                  (                  map                  )                  %>%                  addTiles                  (                  )                  %>%                  addPolygons                  (                  fillColor                  =                  ~                  pal                  (                  variableplot                  ),         color                  =                  "white",         dashArray                  =                  "iii",         fillOpacity                  =                  0.7,         characterization                  =                  labels                  )                  %>%                  # CHANGE cases by variableplot                  leaflet                  ::                  addLegend                  (                  pal                  =                  pal, values                  =                  ~                  variableplot,         opacity                  =                  0.7, championship                  =                  Zilch                  )                  }                  )                  }                  # shinyApp()                  shinyApp                  (ui                  =                  ui, server                  =                  server                  )                              

Snapshot of the Shiny app after adding reactivity.

Figure fifteen.4: Snapshot of the Shiny app after adding reactivity.

Uploading information

Instead of reading the data at the beginning of the app, we may want to let the user upload his or her ain files. In order to practise that, we delete the code we previously used to read the data, and add together ii inputs that enable to upload a CSV file and a shapefile.

Inputs in ui to upload a CSV file and a shapefile

We create inputs to upload the data with the fileInput() function. fileInput() has a parameter called multiple that tin be set to TRUE to allow the user to select multiple files. It also has a parameter called accept that can be set to a grapheme vector with the type of files the input expects. Here we write two inputs. One of the inputs is to upload the data. This input has id filedata and the input value tin be accessed with input$filedata. This input accepts .csv files.

                                                      # in ui                                                        fileInput(inputId =                    "filedata",                                      label =                    "Upload information. Choose csv file",                                      have =                    c(".csv")),                              

The other input is to upload the shapefile. This input has id filemap and the input value tin be accessed with input$filemap. This input accepts multiple files of blazon '.shp', '.dbf', '.sbn', '.sbx', '.shx', and '.prj'.

                                                      # in ui                                                        fileInput(inputId =                    "filemap",                                      label =                    "Upload map. Choose shapefile",                                      multiple =                    True,                                      accept =                    c('.shp','.dbf','.sbn','.sbx','.shx','.prj')),                              

Note that a shapefile consists of unlike files with extensions .shp, .dbf, .shx etc. When we are uploading the shapefile in the Shiny app, we demand to upload all these files at once. That is, we need to select all the files and then click upload. Selecting only the file with extension .shp does not upload the shapefile.

Uploading CSV file in server()

We utilise the input values to read the CSV file and the shapefile. We do this inside a reactive expression. A reactive expression is an R expression that uses an input value and returns a value. To create a reactive expression we utilize the reactive() function which takes an R expression surrounded past braces ({}). The reactive expression updates whenever the input value changes.

For example, nosotros read the data with read.csv(input$filedata$datapath) where input$filedata$datapath is the information path contained in the value of the input that uploads the data. We put read.csv(input$filedata$datapath) within reactive(). In this fashion, each time input$filedata$datapath is updated, the reactive expression is reexecuted. The output of the reactive expression is assigned to data. In server(), data tin can be accessed with data(). data() will be updated each time the reactive expression that builds is reexecuted.

Uploading shapefile in server()

We also write a reactive expression to read the map. We assign the result of the reactive expression to map. In server(), nosotros admission the map with map(). To read the shapefile, nosotros use the readOGR() function of the rgdal package. When files are uploaded with fileInput() they have different names from the ones in the directory. We start rename files with the bodily names and so read the shapefile with readOGR() passing the name of the file with .shp extension.

                                  # in server()                  map                  <-                  reactive                  (                  {                  # shpdf is a data.frame with the proper name, size, type and datapath                  # of the uploaded files                  shpdf                  <-                  input                  $                  filemap                  # The files are uploaded with names                  # 0.dbf, 1.prj, 2.shp, 3.xml, 4.shx                  # (path/names are in column datapath)                  # We need to rename the files with the actual names:                  # fe_2007_39_county.dbf, etc.                  # (these are in column name)                  # Name of the temporary directory where files are uploaded                  tempdirname                  <-                  dirname                  (                  shpdf                  $                  datapath                  [                  1                  ]                  )                  # Rename files                  for                  (                  i                  in                  1                  :                  nrow                  (                  shpdf                  )                  )                  {                  file.rename                  (                  shpdf                  $                  datapath                  [                  i                  ],                  paste0                  (                  tempdirname,                  "/",                  shpdf                  $                  name                  [                  i                  ]                  )                  )                  }                  # Now we read the shapefile with readOGR() of rgdal parcel                  # passing the name of the file with .shp extension.                  # We utilise the function grep() to search the pattern "*.shp$"                  # inside each element of the grapheme vector shpdf$name.                  # grep(pattern="*.shp$", shpdf$name)                  # ($ at the cease denote files that stop with .shp,                  # non only that incorporate .shp)                  map                  <-                  readOGR                  (                  paste                  (                  tempdirname,                  shpdf                  $                  name                  [                  grep                  (design                  =                  "*.shp$",                  shpdf                  $                  proper name                  )                  ],     sep                  =                  "/"                  )                  )                  map                  }                  )                              

Handling missing inputs

After adding the inputs to upload the CSV file and the shapefile, we annotation that the outputs in the Shiny app return error messages until the files are uploaded (Figure 15.5). Here we change the Shiny app to eliminate these error messages by including code that avoids to testify the outputs until the files are uploaded.

Snapshot of the Shiny app after adding inputs to upload the data and the map. The Shiny app renders error messages until the files are uploaded.

FIGURE 15.5: Snapshot of the Shiny app after calculation inputs to upload the data and the map. The Shiny app renders error letters until the files are uploaded.

Requiring input files to be available using req()

Start, within the reactive expressions that read the files, we include req(input$inputId) to require input$inputId to be available earlier showing the outputs. req() evaluates its arguments one at a time and if these are missing the execution of the reactive expression stops. In this way, the value returned by the reactive expression volition not be updated, and outputs that utilize the value returned by the reactive expression volition not exist reexecuted. Details on how to apply req() are in the RStudio website.

We add req(input$filedata) at the starting time of the reactive expression that reads the data. If the data has not been uploaded all the same, input$filedata is equal to "". This stops the execution of the reactive expression, and then data() is not updated, and the output depending on data() is not executed.

                                  # in ui. First line in the reactive() that reads the data                  req                  (                  input                  $                  filedata                  )                              

Similarly, nosotros add req(input$filemap) at the beginning of the reactive expression that reads the map. If the map has non been uploaded still, input$filemap is missing, the execution of the reactive expression stops, map() is not updated, and the output depending on map() is not executed.

                                  # in ui. Outset line in the reactive() that reads the map                  req                  (                  input                  $                  filemap                  )                              

Checking data are uploaded earlier creating the map

Earlier amalgam the leaflet map, the information has to be added to the shapefile. To practise this, we need to make certain that both the data and the map are uploaded. Nosotros can exercise this past writing at the beginning of renderLeaflet() the following code.

When either data() or map() are updated, the instructions of renderLeaflet() are executed. And so, at the beginning of renderLeaflet() it is checked whether either data() or map() are Null. If this is TRUE, the execution stops returning Null. This avoids the fault that nosotros would get when trying to add together the data to the map when either of these two elements is Nothing.

Conclusion

In this chapter, nosotros have shown how to create a Shiny app to upload and visualize spatio-temporal data. We have shown how to upload a shapefile with a map and a CSV file with information, how to create interactive visualizations including a table with DT, a map with leaflet and a fourth dimension plot with dygraphs, and how to add reactivity that enables the user to show specific information. The complete lawmaking of the Shiny app is given below, and a snapshot of the Shiny app created is shown in Figure 15.1. We can meliorate the appearance and functionality of the Shiny app by modifying the layout and adding other inputs and outputs. The website http://shiny.rstudio.com/ contains multiple resources that can be used to improve the Shiny app.

                              library                (                shiny                )                library                (                rgdal                )                library                (                DT                )                library                (                dygraphs                )                library                (                xts                )                library                (                leaflet                )                # ui object                ui                <-                fluidPage                (                titlePanel                (                p                (                "Spatial app", fashion                =                "color:#3474A7"                )                ),                sidebarLayout                (                sidebarPanel                (                fileInput                (                inputId                =                "filedata",         label                =                "Upload data. Choose csv file",         have                =                c                (                ".csv"                )                ),                fileInput                (                inputId                =                "filemap",         characterization                =                "Upload map. Choose shapefile",         multiple                =                Truthful,         accept                =                c                (                ".shp",                ".dbf",                ".sbn",                ".sbx",                ".shx",                ".prj"                )                ),                selectInput                (                inputId                =                "variableselected",         label                =                "Select variable",         choices                =                c                (                "cases",                "population"                )                ),                selectInput                (                inputId                =                "yearselected",         label                =                "Select twelvemonth",         choices                =                1968                :                1988                ),                p                (                "Made with",                a                (                "Shiny",         href                =                "http://shiny.rstudio.com"                ),                "."                ),                img                (                src                =                "imageShiny.png",         width                =                "70px", height                =                "70px"                )                ),                mainPanel                (                leafletOutput                (outputId                =                "map"                ),                dygraphOutput                (outputId                =                "timetrend"                ),                DTOutput                (outputId                =                "table"                )                )                )                )                # server()                server                <-                function                (                input,                output                )                {                data                <-                reactive                (                {                req                (                input                $                filedata                )                read.csv                (                input                $                filedata                $                datapath                )                }                )                map                <-                reactive                (                {                req                (                input                $                filemap                )                # shpdf is a information.frame with the name, size, type and                # datapath of the uploaded files                shpdf                <-                input                $                filemap                # The files are uploaded with names                # 0.dbf, one.prj, 2.shp, 3.xml, iv.shx                # (path/names are in cavalcade datapath)                # We demand to rename the files with the actual names:                # fe_2007_39_county.dbf, etc.                # (these are in column proper noun)                # Name of the temporary directory where files are uploaded                tempdirname                <-                dirname                (                shpdf                $                datapath                [                ane                ]                )                # Rename files                for                (                i                in                one                :                nrow                (                shpdf                )                )                {                file.rename                (                shpdf                $                datapath                [                i                ],                paste0                (                tempdirname,                "/",                shpdf                $                name                [                i                ]                )                )                }                # Now nosotros read the shapefile with readOGR() of rgdal package                # passing the proper noun of the file with .shp extension.                # We utilise the office grep() to search the design "*.shp$"                # within each chemical element of the character vector shpdf$proper noun.                # grep(blueprint="*.shp$", shpdf$name)                # ($ at the end denote files that terminate with .shp,                # non only that contain .shp)                map                <-                readOGR                (                paste                (                tempdirname,                shpdf                $                name                [                grep                (pattern                =                "*.shp$",                shpdf                $                proper name                )                ],       sep                =                "/"                )                )                map                }                )                output                $                table                <-                renderDT                (                data                (                )                )                output                $                timetrend                <-                renderDygraph                (                {                data                <-                data                (                )                dataxts                <-                Cypher                counties                <-                unique                (                information                $                county                )                for                (                l                in                1                :                length                (                counties                )                )                {                datacounty                <-                information                [                data                $                county                ==                counties                [                l                ],                ]                dd                <-                xts                (                datacounty                [,                input                $                variableselected                ],                as.Date                (                paste0                (                datacounty                $                year,                "-01-01"                )                )                )                dataxts                <-                cbind                (                dataxts,                dd                )                }                colnames                (                dataxts                )                <-                counties                dygraph                (                dataxts                )                %>%                dyHighlight                (highlightSeriesBackgroundAlpha                =                0.2                )                ->                d1                d1                $                10                $                css                <-                "  .dygraph-legend > bridge {brandish:none;}  .dygraph-legend > span.highlight { display: inline; }  "                d1                }                )                output                $                map                <-                renderLeaflet                (                {                if                (                is.null                (                data                (                )                )                |                is.null                (                map                (                )                )                )                {                return                (                NULL                )                }                map                <-                map                (                )                data                <-                data                (                )                # Add data to map                datafiltered                <-                data                [                which                (                data                $                year                ==                input                $                yearselected                ),                ]                ordercounties                <-                friction match                (                map                @                data                $                Proper name,                datafiltered                $                county                )                map                @                data                <-                datafiltered                [                ordercounties,                ]                # Create variableplot                map                $                variableplot                <-                as.numeric                (                map                @                data                [,                input                $                variableselected                ]                )                # Create leaflet                pal                <-                colorBin                (                "YlOrRd", domain                =                map                $                variableplot, bins                =                vii                )                labels                <-                sprintf                (                "%south: %one thousand",                map                $                county,                map                $                variableplot                )                %>%                lapply                (                htmltools                ::                HTML                )                l                <-                leaflet                (                map                )                %>%                addTiles                (                )                %>%                addPolygons                (                fillColor                =                ~                pal                (                variableplot                ),         colour                =                "white",         dashArray                =                "3",         fillOpacity                =                0.7,         characterization                =                labels                )                %>%                leaflet                ::                addLegend                (                pal                =                pal, values                =                ~                variableplot,         opacity                =                0.7, title                =                NULL                )                }                )                }                # shinyApp()                shinyApp                (ui                =                ui, server                =                server                )                          

lindemanwerces.blogspot.com

Source: https://www.paulamoraga.com/book-geospatial/sec-shinyexample.html

0 Response to "Using File Uploaded in Rshiny as Data for R"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel