Suggestions for fileInput to work on Shiny ??

Hello,

The code below is generating a scatterplot from a shapefile file. It is generating normally (see the attached image). However, instead of inserting the file directory directly into the code, I would like to insert the file through a fileInput. I inserted the fileInput in the code, but I would like help in making it work. I inserted the shapefile in my github so that you can take the test if you can (https://github.com/JovaniSouza/JovaniSouza5).

Thank you so much!

library(shiny)
library(ggplot2)
library(readxl)
library(shinythemes)
library(rdist)
library(geosphere)
library(rgdal)

function.cl<-function(df,k){
 
  shape<-readOGR(dsn="C:/Users/Jovani Souza/Documents/Test",layer="Export_Output_3") 
  df<-shape@data
  
  #clusters
  coordinates<-df[c("Latitude","Longitude")]
  d<-as.dist(distm(coordinates[,2:1]))
  fit.average<-hclust(d,method="average") 
  clusters<-cutree(fit.average, k) 
  nclusters<-matrix(table(clusters))  
  df$cluster <- clusters 
  
  #all cluster data df1 and specific cluster df_spec_clust
  df1<-df[c("Latitude","Longitude")]
  df1$cluster<-as.factor(clusters)
  
  #Colors
  my_colors <- rainbow(length(df1$cluster))
  names(my_colors) <- df1$cluster
  
  #Scatter Plot for all clusters
  g <- ggplot(data = df1,  aes(x=Longitude, y=Latitude, color=cluster)) + 
    geom_point(aes(x=Longitude, y=Latitude), size = 4) +
    scale_color_manual("Legend", values = my_colors)
  plotGD <- g
  
  
  return(list(
    "Plot" = plotGD
  ))
}

ui <- bootstrapPage(
  navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
             "Cl", 
             tabPanel("Solution",
                      fileInput("shp", h3("Shapefile Import"), multiple = TRUE, accept = c('.shp', '.dbf','.sbn', '.sbx', '.shx', '.prj')),
                      sidebarLayout(
                        sidebarPanel(
                          
                          sliderInput("Slider", h5(""),
                                      min = 2, max = 4, value = 3),
                        ),
                        mainPanel(
                          tabsetPanel(      
                            tabPanel("Solution", plotOutput("ScatterPlot"))))
                        
                      ))))

server <- function(input, output, session) {
  
  Modelcl<-reactive({
    function.cl(df,input$Slider)
  })
  
  output$ScatterPlot <- renderPlot({
    Modelcl()[[1]]
  })
  
}

shinyApp(ui = ui, server = server)

I thought of inserting some reactive similar to what I did below in my server, but it didn't work either.

Modelcl <- eventReactive(input$shp,{
    function.cl(input$shp,input$Slider)
  })
  

Every help is welcome.

Thank you!

Have you read the documentation and example of fileInput?
https://shiny.rstudio.com/reference/shiny/latest/fileInput.html
it loads the file to a temp location and gives you the path that it was stored to, and its that path that you should access and pass to some function that loads data to memory from file paths.

seems like you've jumbled the order of parameters. the dataframe passed into function.cl would be the content of input$slider according to your definitino of function.cl and the way you wrote this call

Thanks a lot for the help nirgrahmuk.

Best regards.

Just one nirgrahamuk thing: I tested it a few times and generated the scatterplot normally, but I tested it again an error appears: length (dsn) == 1L is not TRUE (image below). Do you know why this happens ?? Thanks again.

you changed nothing ?
it randomly works sometimes and fails others ?
dsn is being given path_to_readOGR, it makes sense that this should be a single character string, and not a vector with multiple entries, which is what your error implies.

Yes, it's working randomly, I haven't changed anything in the code. I tested it a few times it worked, sometimes it gives this error above.

I guess you want to see in your console what you are passing

function.cl<-function(path_to_readOGR,k){

  print("path_to_readOGR is")
  str(path_to_readOGR)

  shape<-readOGR(dsn=path_to_readOGR)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Sorry, really, I ended up writing it wrong. I adjusted in the code above. However, it is still not working. I inserted the shapefile above for download if you can to do some testing. I have done it in several ways, I have read several documents, but so far nothing. I have an excel spreadsheet with the same data as the shapefile, and I did a fileInput through excel, and it worked too, just by shapefile I couldn't. Would you help me??

can I ask why you made a rar file rather than say gzip or, zip ?

I updated the code, to make it simple. I removed Filter 1 that was not necessary for the problem I want to solve.

Because it was easier for me, if you want I can create it in another format you want. Anyway, I left it now in zip format too. Thanks again!

if i save shapefile.zip to my computer, then using the fileinput in the app I can browse to and choose it, and it imports succesfully.

library(shiny)
library(ggplot2)
library(readxl)
library(shinythemes)
library(rdist)
library(geosphere)
library(rgdal)


function.cl<-function(path_to_readOGR,k){
 
  shape<-readOGR(dsn=path_to_readOGR)
  df<-shape@data
  
  #clusters
  coordinates<-df[c("Latitude","Longitude")]
  d<-as.dist(distm(coordinates[,2:1]))
  fit.average<-hclust(d,method="average") 
  clusters<-cutree(fit.average, k) 
  nclusters<-matrix(table(clusters))  
  df$cluster <- clusters 
  
  #all cluster data df1 and specific cluster df_spec_clust
  df1<-df[c("Latitude","Longitude")]
  df1$cluster<-as.factor(clusters)
  
  #Colors
  my_colors <- rainbow(length(df1$cluster))
  names(my_colors) <- df1$cluster
  
  #Scatter Plot for all clusters
  g <- ggplot(data = df1,  aes(x=Longitude, y=Latitude, color=cluster)) + 
    geom_point(aes(x=Longitude, y=Latitude), size = 4) +
    scale_color_manual("Legend", values = my_colors)
  plotGD <- g
  
  
  return(list(
    "Plot" = plotGD
  ))
}

ui <- bootstrapPage(
  navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
             "Cl", 
             tabPanel("Solution",
                      fileInput("shp", 
                                h3("Shapefile Zip Import"), 
                                multiple = FALSE,
                                accept = c('.zip')),
                      sidebarLayout(
                        sidebarPanel(
                          
                          sliderInput("Slider", h5(""),
                                      min = 2, max = 4, value = 3),
                        ),
                        mainPanel(
                          tabsetPanel(      
                            tabPanel("Solution", plotOutput("ScatterPlot"))))
                        
                      ))))

server <- function(input, output, session) {
  
Modelcl <- reactive({
  req(input$shp)
  mytempdir <- tempdir()
  unzip(input$shp$datapath, exdir = mytempdir)
  shape_path <- dir(path = mytempdir, pattern = ".shp$")
  function.cl(
    path_to_readOGR = file.path(
      mytempdir,
      shape_path
    ),
    k = input$Slider
  )
})
  output$ScatterPlot <- renderPlot({
    Modelcl()[[1]]
  })
}

shinyApp(ui = ui, server = server)
1 Like