我正在对我闪亮的应用程序进行一些修改,我遇到的问题是我无法使用tryCatch以下方法处理错误:
tryCatch({
# expr
},
error = function(e) {
# handle the error
}
Run Code Online (Sandbox Code Playgroud)
我在我的应用程序中使用 Apriori 算法,当用户选择一个数据集时,他还可以调整 和 的值min-support,min-confidence但有时使用其中的某些值,apriori 算法返回 0 规则,并且在尝试绘制关联规则图。
到目前为止,这是我的代码的一小部分:
...
...
...
rules <- reactive({
validate(
need(input$file, "Please choose a data set")
)
transactions = read.transactions(
file = file(input$file$datapath),
format = "basket",
sep = ","
)
minValue <- min(length(transactions),input$visualization)
rules <-
apriori(transactions[0:minValue],
parameter = list(
support = input$min_supp,
confidence = input$min_conf
))
print(length(transactions[0:minValue]))
return(rules)
})
Run Code Online (Sandbox Code Playgroud)
output$graphChart <- renderPlot({
Sys.sleep(1)
validate(
need(input$file, "Please choose a data set")
)
set.seed(42)
# validate(
# need(length(rules()) == 0, "zero rules")
# )
tryCatch({
plot(rules(), method = "graph")
})
error = function(condition){
print('there was an error')
}
})
Run Code Online (Sandbox Code Playgroud)
但没有任何改变,我仍然收到错误,并且 R 工作室的控制台中没有打印任何消息
我尝试了这个, 但它并不能帮助我消除错误,顺便说一句,当没有找到规则时,我也会在其他选项卡上收到错误。
正如猪肉在他的评论中提到的,我尝试过:
output$graphChart <- renderPlot({
Sys.sleep(1)
validate(
need(input$file, "Please choose a data set")
)
set.seed(42)
# validate(
# need(length(rules()) == 0, "zero rules")
# )
tryCatch({
plot(rules(), method = "graph",)
})
error=function(cond) {
message(cond)
return(NA)
}
warning=function(cond) {
message(cond)
# Choose a return value in case of warning
return(NULL)
}
})
Run Code Online (Sandbox Code Playgroud)
并且错误再次存在,
有人能帮助我吗 ?
任何建议或意见将不胜感激!
谢谢。
这是一个如何使用tryCatchblock 的小例子。我们将用来showNotification通知用户错误
library(shiny)
ui <- fluidPage(
sidebarPanel(width = 2,
selectInput("data","data",choices = c(1,2),selected = 1)
),
mainPanel(
plotOutput("graphChart")
)
)
server <- function(input, output, session) {
rules <- reactive({
if(input$data == 1){
return(mtcars$mpg)
}else{
"some error"
}
})
output$graphChart <- renderPlot({
tryCatch({
plot(rules())
}, warning = function(w) {
showNotification('there was a warning','',type = "error")
return()
}, error = function(e) {
showNotification('there was an error','',type = "error")
return()
}, silent=TRUE)
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)