我的 ggvis 图取决于几个输入字段,它们的工作方式类似于输入数据的过滤器。对于某些组合,结果数据框为空,ggvis 抛出错误并破坏整个应用程序。
我试着把
if(nrow(inputdataframe) == 0) return NULL
if(nrow(inputdataframe) == 0) return ggvis()
这没有帮助。在这种情况下,正确的返回参数是什么(我想要一个空图或一些文本消息)?
服务器
effvis <- reactive ({
dta <- siteeff()
if(nrow(dta) == 0) return(NULL)
dta %>%
ggvis(~param.value, ~yvar) %>%
layer_points( size := 50, size.hover := 200) %>%
set_options(width = 800, height = 500)
})
effvis %>% bind_shiny("effplot")
ui.R--
ggvisOutput("effplot")
更新
当数据为空时,我不想显示所有数据(如建议的 here )这很令人困惑
最佳答案
所以在你的代码中看到更多的逻辑会很有帮助。我想我会说一般来说,了解响应式(Reactive)表达式在程序逻辑上下文中的工作方式非常重要。我会尝试在 Shiny 的主页上阅读尽可能多的代码。这是我写的一个快速脚本,我认为它可以满足您的要求。干杯。
全局.r
library(plyr)
library(dplyr)
exp <- data.frame(Ind=rep(c("a","b"),each=50),val1=rgamma(100,10,5),val2=rnorm(100,2,3.5))
服务器文件
library(shiny)
library(ggvis)
shinyServer(function(input, output, session) {
output$selectO <- renderUI({ selectInput(inputId="selectI", label = h4("Level to Plot"),
choices = list("a","b","c"),selected="a")
})
observe({
if(!is.null(input$selectI)){
expfilter <- reactive({
vals <- exp %>% filter(Ind == input$selectI)
return(vals)
})
if(nrow(expfilter())==0){
fail <- reactive({ return("filter failed") })
output$trouble <- renderText({fail()}) # notice the use of () since fail is a function. when you want to grab the values of reactives use the ()
} else {
success <- reactive({ return("good") })
output$trouble <- renderText({success()})
P1 <- reactive({
expfilter %>% ggvis(~val1, ~val2) %>%
add_axis("x",title="Var1",title_offset=45,properties=axis_props(labels=list(fontSize = 13, fontWeight = "bold"),title=list(fontSize = 15))) %>%
add_axis("y",properties=axis_props(labels=list(fontSize = 13, fontWeight = "bold")))
})
P1 %>% bind_shiny("plot1")
}
}
})
})
用户界面
library(shiny)
shinyUI(fluidPage(
column(3,
wellPanel(
uiOutput("selectO")
)
),
column(9,
wellPanel(
ggvisOutput("plot1")),
wellPanel(h6("How Did the Filter Do"),
textOutput("trouble")
)
)
)
)
关于r - 当数据为空时从 ggvis 返回的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997720/