【发布时间】:2017-04-17 21:06:05
【问题描述】:
我试图用一些 ifelse 条件来更新一个值。
例如,在下面的代码中,我只想在响应式“decim_factor”更改其值时更新响应式“乘数”,而不是仅更新它。我尝试将带有“decim_factor”的observeEvent用作eventExpr,但没有成功。
library(shiny)
rm(list = ls())
ui <- shinyUI(pageWithSidebar(
headerPanel("Click the button"),
sidebarPanel(
numericInput("index","Numeric Input",1),
p("This is the criteria to change the decim_factor depending on numericInput"),
br(),
p(" num_input >= 20 - decim_factor=3"),
p("20 > num_input >= 10 - decim_factor=2"),
p("10 > num_input - decim_factor=1")
),
mainPanel(
verbatimTextOutput("decim"),
verbatimTextOutput("multip")
)
))
server <- shinyServer(function(input, output) {
decim_factor <- reactive({
num_input <- input$index
if(num_input>=20) {decim_factor <- 3}
else if(10<=num_input & num_input<20) {decim_factor <- 2}
else decim_factor <- 1
as.numeric(decim_factor)
})
#I was trying to calculte the 'multiplier' only if 'decim_factor' changes its value
#and not if it is updated
#
#I tried to use observeEvent, depending on decim_factor() but it didn't work
#If I put the observeEvent function as comment it works, but the multiplier
#updates every time I change the numeric_input
observeEvent(decim_factor(),{
multiplier <- reactive({
decim_factor()*10
})
})
#The outputs come with da Sis.time() just to check if the values are updated
output$decim <- renderText({paste("Decim = ",decim_factor(), ";",Sys.time())})
output$multip <- renderText({paste("Muliplier =", multiplier(), ";",Sys.time())})
})
shinyApp(ui,server)
【问题讨论】:
-
试试
multiplier <<- reactive({...,否则全局环境中没有设置乘数,也可以使用reactiveValues -
“乘数
标签: r if-statement shiny