0

如果在 fileInput 中加载的数据库与我的代码的理想基础不对应,我想知道如何创建一般警报,因为可能存在几个问题,例如: [.data.frame 中的错误:选择了未定义的列,hclust 中的错误:NA / NaN / Inf 以及其他错误。那么,有没有办法做到这一点?如果加载的数据库有问题,是否显示警报?我在下面插入了一个可执行代码,只是为了测试。可以从以下网站下载数据库:

https://github.com/JovaniSouza/JovaniSouza5/blob/master/Example.xlsx

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

function.cl<-function(df,k){
  
  #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("data", h3("Excel import")), 
                      sidebarLayout(
                        sidebarPanel(
                          
                          sliderInput("Slider", h5(""),
                                      min = 2, max = 4, value = 3),
                        ),
                        mainPanel(
                          tabsetPanel(      
                            tabPanel("Solution", plotOutput("ScatterPlot"))))
                        
                      ))))

server <- function(input, output, session) {
  
  v <- reactiveValues(df = NULL)
  observeEvent(input$data, {
    v$df <- read_excel(input$data$datapath)
  })
  
  
  Modelcl<-reactive({if (!is.null(v$df)) {
    function.cl(v$df,input$Slider)
  }
  })
  
  
  output$ScatterPlot <- renderPlot({
    Modelcl()[[1]]
  })
  
  
}

shinyApp(ui = ui, server = server)
4

1 回答 1

1

也许是这样的(我没有尝试过)。这需要shinyWidgets用于sendSweetAlert.

Modelcl <- reactive({
  req(v$df)
  out <- NULL
  tryCatch({
    out <<- function.cl(v$df, input$Slider)
  }, error = function(e){
    sendSweetAlert(
      session, 
      "An error occured",
      "Try to upload another file.", 
      "error"
    )
  })
  out
})

output$ScatterPlot <- renderPlot({
  req(Modelcl())
  Modelcl()[[1]]
})
于 2020-07-01T07:28:24.520 回答