![](/img/trans.png)
[英]How to replace an observeEvent with a more comprehensive reactive function in R Shiny?
[英]How to replace reactive with reactiveVal and ObserveEvent in R Shiny
在研究 R Shiny 时,我发现您可以在没有observeEvent()
) 的情况下使用reactive()
(),如下面的演示代码所示。 但是我正在尝试学习组合的reactiveVal()
和observeEvent()
函数的使用。
在演示代码中,用户可以通过单选按钮选择仅显示数据帧的前 4 行(称为“数据”)。 超级简单。 它可以正常工作,因为在 server 部分中仅使用reactive()
而没有observeEvent()
编写。 但我试图用reactiveVal()
和observeEvent()
的组合替换它,如演示代码中的注释掉 (#) 部分所示。 我究竟做错了什么? 如何使reactiveVal()
和observeEvent()
一起工作以产生相同的结果?
演示代码:
library(shiny)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9)
)
ui <- fluidPage(
h4(strong("Base data frame:")),
tableOutput("data"),
radioButtons(inputId = "showData",
label = "Show from original dataframe:",
choiceNames = c('All','First 4 rows'),
choiceValues = c('All','Rows'),
selected = 'All',
inline = TRUE
),
h4(strong("Reactive results:")),
tableOutput("choices"),
)
server <- function(input, output, session) {
output$data <- renderTable(data)
# Choices <- reactiveVal()
#
# observeEvent(
# input$showData, {
# if(input$showData == 'Rows'){Choices <- data[1:4,]} else {Choices <- data}
# }
# )
Choices <- reactive(if(input$showData == 'Rows'){data[1:4,]} else {data})
output[["choices"]] <- renderTable({Choices()}
)
}
shinyApp(ui, server)
以下是已解决的更正代码,包含 Limey 的评论:
library(shiny)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9)
)
ui <- fluidPage(
h4(strong("Base data frame:")),
tableOutput("data"),
radioButtons(inputId = "showData",
label = "Show from original dataframe:",
choiceNames = c('All','First 4 rows'),
choiceValues = c('All','Rows'),
selected = 'All',
inline = TRUE
),
h4(strong("Reactive results:")),
tableOutput("choices"),
)
server <- function(input, output, session) {
output$data <- renderTable(data)
# The below uses combo of reactiveValues() and observeEvent(), per Limey's comments:
rv <- reactiveValues(choices=c()) # reactiveValues is for multiple reactive values, and reactiveVal is for a single reactive value
observeEvent(input$showData, {
if(input$showData == 'Rows'){rv$choices <- data[1:4,]}
else {rv$choices <- data}
}
)
output[["choices"]] <- renderTable({ rv$choices })
}
shinyApp(ui, server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.