R 我在"Renderplot"内创建了一个数据帧,并希望在此之外访问它。如何使其具有反应性?



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

我试过简单地将生成数据帧的代码块插入到一个反应函数中,并在信息框和renderplot函数中调用它,但这两种方法都不起作用。是否可以创建一个反应数据帧?如果是,我可以只访问数据帧中的一个值吗?我对这一切都很陌生,所以如果下面的代码很乱,我很抱歉。

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((将其调用到绘图中

最新更新