2017-07-24 64 views
1

我有一个反应性对象,当用户单击GO按钮时,我想修改它。我试过这个代码,Per给出了一个很好的结果。 现在我想考虑第一个修改多个修改,所以看起来我应该每次修改它时都要保存RA_sShiny:如何修改反应性对象

我该如何处理这个问题?

代码

shinyServer(function(input, output) { 

    RA_s <- reactive({ 
    read.csv("C:/alay/Desktop/RA.csv") 
    }) 

    Per <- reactive({ 
    if(input$go == 0) return(RA_s()) 
    else { 
     c = RA_s() 
     c[1] = rep(0,nrow(RA_s())) 
    } 
    c 
    }) 

     }) 


sidebar <- dashboardSidebar(
    sidebarMenu(
    menuItem("Download", tabName = "d") 
) 
body<- dashboardBody(
    tabItems(
    tabItem(tabName = "d", 
     actionButton("go",'GO!') ) 
) 
dashboardPage(
dashboardHeader(title = "Valo"), 
sidebar, 
body 
) 

回答

0

我用reactiveValues代替reactiveVal和它完美的作品

感谢@Florian

server <- shinyServer(function(input, output) { 

    in_data <- reactive({ 
     inFile <- input$e 
     read.csv(inFile$datapath) 
    }) 

    RA_s <- reactiveValues(ra = NULL) 
    RA_s$ra <- in_data() # intiialize the reactiveValue 


    # an observer to update the reactiveValue RA_s 
    observeEvent(input$go, { 
    # read the current value 
    current_value <- RA_s$ra 

    # update the value 
    new_value <- current_value[-(1)] 

    # write the new value to the reactive value 
    RA_s$ra <- new_value 


    }) 
    output$x <- renderDataTable({ 
    RA_s$ra 
    }) 
}) 


ui <- shinyUI(
    fluidPage(
    fileInput('e', 'E'), 
    actionButton("go","GO!"), 
    dataTableOutput('x')  
) 
) 
shinyApp(ui,server) 
0

为了存储和更新反应对象,你可以使用reactiveVal或reactiveValues。

我创建了一个简单的例子,这是如何与你的目标工程记:

server <- shinyServer(function(input, output) { 

    RA_s <- reactiveVal() 
    RA_s(1) # intiialize the reactiveVal, place your csv read here. 


    # an observer to update the reactiveVal RA_s 
    observeEvent(input$go, { 
    # read the current value 
    current_value <- RA_s() 

    # update the value 
    new_value <- current_value +1 

    # write the new value to the reactive value 
    RA_s(new_value) 

    # print to console, just to check if it updated. 
    print(paste0("Succesfully updated, new value: ",RA_s())) 
    }) 

}) 


ui <- shinyUI(
    fluidPage(
    actionButton("go","GO!")  
) 
) 
shinyApp(ui,server) 

希望这有助于!

+0

我想这个代码,但没有奏效。我尝试修改反应性对象时遇到了同样的错误:传递给reactiveValues()的所有参数都必须命名为' –

+0

我很乐意提供帮助,但您应该提供一些示例数据,以便我可以重现你的错误。特别是,确保你提供了一些数据,看看[这里](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Florian

+0

它在我使用直接在代码中导入函数,但是当我通过一个'fileInput'时,我得到了这个错误'.getReactiveEnvironment()$ currentContext:没有一个活动的被动上下文不允许的操作(你试图做一些只能从内部一个被动的表达或观察者)。“所以我不认为数据有问题。错误在于这一行'new_value < - current_value [ - (1)]'。 (相同的代码没有使用'fileinput'工作) –