【问题标题】:Insert reactive for fileInput (shapefile)为fileInput(shapefile)插入反应式
【发布时间】:2020-06-23 06:28:04
【问题描述】:

下面的代码从 shapefile 文件生成散点图。它正在正常生成(见附图)。但是,我不想将文件目录直接插入到代码中,而是想通过 fileInput 插入文件。我在下面插入了 fileInput,但我想帮助调整我的服务器。 我认为有必要调整与反应相关的东西。

非常感谢!

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

function.cl<-function(df,k){
  
  shape<-readOGR(dsn="C:/Users/Jose 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)

【问题讨论】:

  • 你想在服务器上做什么?加载选定的文件?
  • 感谢您的回答。我想在通过 fileInput 上传文件后进行聚类。您不必为此文件输入在服务器中进行反应吗?
  • 为什么 function.cl 有一个 df 参数,你在函数的第二行覆盖了它?

标签: r shiny


【解决方案1】:
  1. 在 function.cl 中添加一个新的 path 参数,删除因为直接在函数中分配而未使用的 df 参数
  2. 在服务器中使用 `eventReactive' :
  Modelcl <- eventReactive(input$shp,{
    req(input$shp)
    mydir <- tempdir()
    on.exit(unlink(mydir))
    print(paste("names:",input$shp$name))
    file.copy(input$shp$datapath,file.path(mydir, input$shp$name) )
    function.cl(input$Slider,mydir)
    
  })

困难在于 readOGR 需要一个路径,但 fileInput 返回文件。

解决方法是创建一个临时目录以获取路径(在服务器上),将fileInput 文件复制到其中并将此临时目录的路径提供给readOGR进行进一步处理。

这适用于您提供的示例文件:

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

function.cl<-function(k,path,filename){
  print(dir(path))
  shape<-readOGR(dsn=path,layer=filename) 
  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,input$Filter1)
  # })
  Modelcl <- eventReactive(c(input$shp, input$Slider),{
    req(input$shp)
    tmpdir <- tempdir()
    on.exit(unlink(tmpdir))
    filename <- substr(input$shp$name[1],1,nchar(input$shp$name[1])-4)
    file.copy(input$shp$datapath,file.path(tmpdir,input$shp$name) )
    function.cl(input$Slider,tmpdir,filename)
    
  })
  
  output$ScatterPlot <- renderPlot({
    Modelcl()[[1]]
  })
  
  observeEvent(input$Slider, {
    abc <- req(Modelcl()$Data)
    updateSelectInput(session,'Filter1',
                      choices=sort(unique(abc$cluster)))
  }) 
  
}

shinyApp(ui = ui, server = server)

【讨论】:

  • 感谢您的回复。我相信这是方法,但它仍然没有成功。此代码:df &lt;-shape @ data 需要在代码中,因为它将 shapefile 转换为 data.frame。如果您可以插入所有代码以及您所做的更改,我将不胜感激。
  • 感谢 Waldi 更新答案。我还在做测试,但我还没有做。我哥也在帮我,把这个issue的shapefile文件插入到他的github(github.com/JovaniSouza/JovaniSouza5/blob/master/shapefile.rar)。所以,如果可以的话,我相信您也可以更轻松地进行模拟。再次感谢。
  • 感谢您提供的文件:哪些文件应该读 OGR 打开?
  • 朋友您好,zip 中的所有文件都是 1 个 shapefile 的一部分。一个 shapefile 平均由 6 到 8 个文件组成。公式中dsn为shapefile的保存路径,Export_Output_3为shapefile的名称。因此,readOGR 不是只选择一个特定文件,而是选择构成 shapefile 的所有文件。
  • 好的,知道了,所以你不是在寻找文件输入,而是在寻找路径
猜你喜欢
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
相关资源
最近更新 更多