-
第一种可能性 -
conditionalPanel
如果按下了actionButton,我们希望显示plotOutput。更具体地说,如果input.Next > 0。此条件在javaScript 中进行评估,因此我们的语法略有不同——我们在输入后使用. 而不是$,并使用括号。
conditionalPanel(
condition = "input.Next * 1 > 0",
plotOutput("test")
)
然而,我们将input.Next 乘以一是很奇怪的。这是必要的,因为input.Next 期望一个数字,也返回属性。似乎 JavaScript 不知道如何处理这个问题……但是乘法可以解决问题。
[1] 0
attr(,"class")
[1] "integer" "shinyActionButtonValue"
在此示例中,plotOutput立即出现...肯定太快了。
library(shiny)
ui1 <- shinyUI(fluidPage(
sidebarPanel(
conditionalPanel(
condition = "input.Next * 1 > 0",
plotOutput("test")
),
actionButton("Next", "Next")
)
))
server1 <- shinyServer(function(input, output, session) {
output$test <- renderPlot({
pt <- plot(input$Next, 2)
print(input$Next)
print(pt)
})
})
shinyApp(ui1, server1)
-
"Slowing down the train"
在本例中,我们将“减慢”超速行驶的plotOutput。为此,我们需要 shinyjs 包。
首先,我们要将conditionalPanel 包装成一个带有ID 的div,例如animation
div(id = "animation",
conditionalPanel(
condition = "input.Next * 1 > 0",
plotOutput("test")
)
)
然后,在服务器端,我们将按以下方式定义动画:以输入为条件$next div 应该与幻灯片动画一起显示。
observe({
toggle(id = "animation", anim = TRUE, animType = "slide",
time = 0.5, condition = input$Next > 0)
})
完整示例:
ui2 <- shinyUI(fluidPage(
# we need to include this function in order to use shinyjs functions
useShinyjs(),
sidebarPanel(
actionButton("Next", "Next"),
div(id = "animation",
conditionalPanel(
condition = "input.Next * 1 > 0",
plotOutput("test"),
sliderInput("manipulate", "slider", min = 0, max = 1, value = 1)
)
)
)
))
server2 <- shinyServer(function(input, output, session) {
# Introduce gently the div with an id = "animation" and its all content.
observe({
toggle(id = "animation", anim = TRUE, animType = "slide",
time = 0.5, condition = input$Next > 0)
})
# We could animate only the plotOutput with "toogle(id = test")"
# - it would work as well, but for the first time the plot is shown
# way we would get an errors with margins.
output$test <- renderPlot({
#plot(input$Next, 2)
ggplot(iris, aes(x = Species)) + geom_bar(alpha = input$manipulate)
})
})
shinyApp(ui2, server2)
renderUI
正如您所指出的,另一种可能性是使用函数renderUI。如果您想一次渲染多个元素,则必须将它们包装到 list 中,如下例所示:
library(shiny)
library(ggplot2)
ui3 <- shinyUI(fluidPage(
sidebarPanel(
uiOutput("dynamic"),
actionButton("Next", "Next")
)
))
server3 <- shinyServer(function(input, output, session) {
output$dynamic <- renderUI({
if (input$Next > 0) {
# if we want to render more element, we need the list
list(
plotOutput("test"),
sliderInput("manipulate", "slider", min = 0, max = 1, value = 1)
)
}
})
output$test <- renderPlot({
#plot(input$Next, 2)
ggplot(iris, aes(x = Species)) + geom_bar(alpha = input$manipulate)
})
})
shinyApp(ui3, server3)