2017-07-24 89 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'工作) –