我很难在Shiny Apps中使用反应式表达。我正在从滑块输入创建一个饼图。这一切都很好,但标签重叠。为了避免这种情况,我想在输入为零时使用标签“”。困难在于我无法在if-then语句中嵌入反应式表达式。
这是一个MWE ......
档案“ui.R”......
library(shiny)
shinyUI(fluidPage(
titlePanel("Exposure to English calculator"),
sidebarLayout(
sidebarPanel(
h3("Sleeping"),
sliderInput("sleep", "How long does your child sleep every day?",
min=0, max=15, value=0, step = 0.5),
h3("School"),
sliderInput("school", "How long does your child spend in school?",
min = 0, max = 50, value=0, step = 0.5)
),
mainPanel(
plotOutput("plot")
)
)
))
文件server.R ...
library(shiny)
values <- c(1,2)
# Define server logic for slider examples
shinyServer(function(input, output) {
total_sleep <- reactive({7*input$sleep})
pieLabels<-c("sleep", "school", "other")
if(total_sleep() == 0) {
pieLabels[1] <- ""
}
output$plot <- renderPlot({
pie(c(total_sleep(), input$school, 50),
labels = pieLabels,
col = c("deepskyblue", "orange"),
height = 1500
)
})
})
由于“if”表达式导致编译崩溃,即使我在其后面放置括号,以表明它是从反应式表达式派生的。
提前致谢。
答案 0 :(得分:0)
您可以将所有total_sleep
代码和条件语句放在renderPlot
函数中:
library(shiny)
app <- shinyApp(
ui = shinyUI(fluidPage(
titlePanel("Exposure to English calculator"),
sidebarLayout(
sidebarPanel(
h3("Sleeping"),
sliderInput("sleep", "How long does your child sleep every day?",
min=0, max=15, value=0, step = 0.5),
h3("School"),
sliderInput("school", "How long does your child spend in school?",
min = 0, max = 50, value=0, step = 0.5)
),
mainPanel(
plotOutput("plot")
)
)
)),
server = shinyServer(function(input, output) {
output$plot <- renderPlot({
total_sleep <- 7*input$sleep
pieLabels<-c("sleep", "school", "other")
if(total_sleep == 0) {
pieLabels[1] <- ""
}
pie(c(total_sleep, input$school, 50),
labels = pieLabels,
col = c("deepskyblue", "orange")
)
})
}))
runApp(app)
请注意,我从height
删除了pie
,因为该参数不存在且会发出警告。