R shiny - 我在 "Renderplot" 中创建了一个数据框,并希望在这个之外访问它。我怎样才能让它反应?

R shiny - I created a dataframe within "Renderplot" and would like to access it outside of this. How can I make it reactive?

我在渲染绘图函数中创建了一个数据框并绘制了它。我想访问此数据框中“基金”列的最后一个值并将其插入到信息框中。在附加的代码中,基金的价值在我的信息框中没有反应。

我试过简单地获取生成数据框的代码块并将其插入到反应函数中,然后在信息框和渲染图函数中调用它,但两者都无法工作。是否可以创建反应式数据框?如果是这样,我可以只从数据框中访问一个值吗?我对所有这一切都很陌生,所以如果以下代码混乱,我深表歉意。

server <- function(input, output) {
  output$line <- renderPlot({
    intrate <- input$int/100    #where I created the data frame
    fund <- as.numeric()
    return <- as.numeric()
    draw <- as.numeric()
    fund[1] <- input$pot
    draw[1] <- input$dd
    age <- c(input$age:94)
    for(i in 1:(95-input$age)){
      draw[i+1] <- draw[i]*(1+input$inf/100)
      return[i] <- fund[i]*intrate
      fund[i+1] <- max(0,fund[i] + return[i] - draw[i]) 
    }
    draw <- head(draw, -1)
    fund<- head(fund,-1)
    data <- as.data.frame(cbind(age, fund, draw, return))
    

#my plot
    ggplot(data = data, mapping = aes(age, fund)) +
      geom_line(color="red", size=1, alpha=0.9, linetype=1) +
      scale_y_continuous(labels = function(x) format(x, scientific = FALSE), limits = c(0,NA))+
      labs(y = "Fund (€)", x = "Age (Years)")+
      theme_light()
  })
  
  output$fad <- renderInfoBox(       ##where I want to access fund for an infobox
    
    infoBox(title = "Fund at Death", paste0(round(tail(fund, n=1),2)), icon = icon("credit-card"),
            color = "blue")
  )
  
}

为了提供背景信息,我正在创建一个退休金提取计算器,其中输入退休年龄并假设 95 岁死亡。

这样应该可行:

server <- function(input, output) {
  data <- reactive({
    intrate <- input$int/100    #where I created the data frame
    fund <- as.numeric()
    return <- as.numeric()
    draw <- as.numeric()
    fund[1] <- input$pot
    draw[1] <- input$dd
    age <- c(input$age:94)
    for(i in 1:(95-input$age)){
      draw[i+1] <- draw[i]*(1+input$inf/100)
      return[i] <- fund[i]*intrate
      fund[i+1] <- max(0,fund[i] + return[i] - draw[i]) 
    }
    draw <- head(draw, -1)
    fund<- head(fund,-1)
    data <- as.data.frame(cbind(age, fund, draw, return))
  })

  output$line <- renderPlot({
  #my plot
    ggplot(data = data(), mapping = aes(age, fund)) +
      geom_line(color="red", size=1, alpha=0.9, linetype=1) +
      scale_y_continuous(labels = function(x) format(x, scientific = FALSE), limits = c(0,NA))+
      labs(y = "Fund (€)", x = "Age (Years)")+
      theme_light()
  })
  
  output$fad <- renderInfoBox(       ##where I want to access fund for an infobox
    
    infoBox(title = "Fund at Death", paste0(round(tail(fund, n=1),2)), icon = icon("credit-card"),
            color = "blue")
  )
  
}

总而言之:您将 data.frame 部分放在反应式表达式中,我们通过引用 data()

将其调用到绘图中