如何使用reactiveValues() 来在闪亮的应用程序中存储更改 [英] How to use reactiveValues() in order to store changes in a shiny app
问题描述
我有一个简单的闪亮应用,我使用 numericInput()
来设置数据帧的行数.然后我使用 selectInput()
"Label"从数据表中选择一个标签,然后使用 textInput() 更改为"更改其名称.问题是,每次我尝试使用 textInput()
更改新标签的名称时,我修改的前一个标签都会返回默认名称.我相信这是因为我的 DF
是在反应式函数中创建的,不能接受子集.我可能需要的是使用 reactiveValues()
来存储以前的值,但我不知道如何使用它,所以我在这里使用 reactive()
以便显示一个工作示例.
I have a simple shiny app in which I use a numericInput()
to set the number of the rows of the dataframe.Then I use a selectInput()
"Label" to select a Label from the datatable and then change its name with textInput() "Change to". The problem is that every time I try to change the name of a new Label using the textInput()
the previous Label that I modified returns to default name. I believe this is happening because my DF
is created inside a reactive function and cannot accept the subsetting. What I probably need is using reactiveValues()
in order to store the previous values but I do not know exactly how to use it so I use reactive()
here in order to display a working example.
library(shiny)
library(DT)
ui <- navbarPage(
"Application",
tabPanel("General",
sidebarLayout(
sidebarPanel(
uiOutput("tex2"),
uiOutput("book3"),
uiOutput("book6")
),
mainPanel(
DT::dataTableOutput("hot3")
)
)))
#server.r
server <- function(input, output,session) {
output$tex2<-renderUI({
numericInput("text2", "#tests", value = 1, min=1)
})
output$book3<-renderUI({
selectInput("bk3", "Label", choices=(paste("Test",1:input$text2)))
})
output$book6<-renderUI({
textInput("bk6", "Change to", value=NULL)
})
rt4<-reactive({
DF <- data.frame(
Test=paste(1:input$text2),
Label=paste("Test",1:input$text2),
stringsAsFactors = FALSE)
if(!is.null(input$bk6) && input$bk6!=""){
DF[DF$Label==isolate(input$bk3), "Label"] <- input$bk6
}
{
DF
}
})
output$hot3 <-DT::renderDataTable(
rt4(),
rownames= FALSE
)
}
推荐答案
这似乎有效
library(shiny)
library(DT)
library(dplyr)
ui <- navbarPage(
"Application",
tabPanel("General",
sidebarLayout(
sidebarPanel(
uiOutput("tex2"),
uiOutput("book3"),
uiOutput("book6"),
actionButton('submit','submit')
),
mainPanel(
DT::dataTableOutput("hot3")
)
)))
server <- function(input, output,session) {
output$tex2<-renderUI({
numericInput("text2", "#tests", value = 1, min=1)
})
output$book3<-renderUI({
selectInput("bk3", "Label", choices=(paste("Test",1:input$text2)) )
})
output$book6<-renderUI({
textInput("bk6", "Change to", value=NULL)
})
values <- reactiveValues(rv = NULL)
observe( { req(input$text2)
Test <-paste(1: input$text2)
Label <- paste("Test",1:input$text2)
values$rv<-data.frame( Test= Test, Label=Label, stringsAsFactors = FALSE)}
)
observeEvent(input$submit,{
if(!is.null(input$bk6) && input$bk6!=""){
values$rv <- values$rv %>%
mutate(Label= ifelse(Label== input$bk3,input$bk6,Label))
}
})
output$hot3 <-DT::renderDataTable( {
datatable(values$rv, rownames=FALSE)
})
}
shinyApp(ui,server)
这篇关于如何使用reactiveValues() 来在闪亮的应用程序中存储更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!