pic*_*ick 6 r r-markdown shiny
当我有传递给renderPlot
(或其他渲染函数)的反应性数据时,数据通常最初是空的,直到发生某些操作。默认渲染通常会在动作发生之前在应用程序中显示错误,因为数据为空,即
错误“x”必须是数字
在这个例子中。是否有一些标准方法可以让渲染函数在没有数据时运行(如果出现错误或只是空白,则可能不会渲染)?我知道我可以麻烦地构建所有反应值,因此输出将为空白,但这似乎是不必要的工作。
rMarkdown 中的示例闪亮
---
title: "Example"
runtime: shiny
output: html_document
---
```{r}
shinyApp(
shinyUI(fluidPage(
inputPanel(
numericInput("n", "n", 10),
actionButton("update", "Update")
),
plotOutput("plot")
)),
shinyServer(function(input, output) {
values <- reactiveValues()
values$data <- c()
obs <- observe({
input$update
isolate({ values$data <- c(values$data, runif(as.numeric(input$n), -10, 10)) })
}, suspended=TRUE)
obs2 <- observe({
if (input$update > 0) obs$resume()
})
output$plot <- renderPlot({
dat <- values$data
hist(dat)
})
})
)
```
Run Code Online (Sandbox Code Playgroud)
您可以使用该exists
函数在尝试绘制变量之前查看变量是否存在,并根据需要进行更改:
renderPlot({
if(exists("values$data")) {
dat <- values$data
} else {
dat <- 0
}
hist(dat)
})
Run Code Online (Sandbox Code Playgroud)