【问题标题】:How to make the plot reactive to user input?如何使情节对用户输入做出反应?
【发布时间】:2021-07-20 22:48:36
【问题描述】:

在下面的超级简单的 MWE 代码中,我试图使绘图对用户滑块输入“句点”产生反应。我尝试了各种不同的observeEvent 迭代,但都没有成功。有人可以帮我做出反应吗?

该图应该在 y 轴上显示 endBal,在 x 轴上显示 periods

另外,在下面的 MWE 代码行中,res <- Reduce(f,seq(periods),init=beginBal,accumulate=TRUE) 没有从滑块输入中获取周期值。为了让 MWE 运行演示,我必须在代码顶部的“定义向量”部分手动定义 periods 变量(例如 periods <- 5)。知道为什么这部分不起作用吗?

library(shiny)

### Define vectors ##############################################################
beginBal       <- 1000
yield_vector   <- c(0.30,0.30,0.30,0.30,0.30,0.28,0.26,0.20,0.18,0.20)
npr_vector     <- c(0.30,0.30,0.30,0.30,0.30,0.30,0.30,0.30,0.30,0.30)
mpr_vector     <- c(0.20,0.20,0.20,0.20,0.20,0.20,0.20,0.20,0.20,0.20)
default_vector <- c(0.10,0.10,0.10,0.10,0.10,0.09,0.08,0.07,0.06,0.05)
### End define vectors ##########################################################

ui <- fluidPage(
  sliderInput(inputId = "periods",
              label = "Periods:",
              min = 1,
              max = 10,
              value = 5),
  plotOutput(outputId = "balancePlot")
  ) # close fluid page

server <- function(input,output){

  ### Generates data for plotting ###############################################
  f      <- function(x,y){x*(1+npr_vector[y]-mpr_vector[y]-default_vector[y]/12)}
  res    <- Reduce(f,seq(periods),init=beginBal,accumulate=TRUE)
  b      <- head(res,-1)
  endBal <- res[-1]
  ### End data for plotting ##################################################### 
    
  output$balancePlot <- renderPlot({plot(endBal)})
  
  } # close server

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    试试这个

    output$balancePlot <- renderPlot({
        f      <- function(x,y){x*(1+npr_vector[y]-mpr_vector[y]-default_vector[y]/12)}
        res    <- Reduce(f,seq(input$periods),init=beginBal,accumulate=TRUE)
        b      <- head(res,-1)
        endBal <- res[-1]
        plot(endBal)
      })
    

    【讨论】:

    • 是的,行得通。相关功能必须位于反应式“renderPlot”下。我会尽量不要忘记这个简单的教训。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多