2017-03-25 44 views
1

我使用Shiny應用程序中的htmlWidgets包中的onRender()函數。我試圖保存在給定的onRender()函數調用中創建的某些對象,以便在給定的onRender()函數調用之外使用它們。在htmlWidgets中保存在onRender()函數中創建的對象

以下是我的MWE。我在onRender()函數中創建了一個名爲val2的對象,它只是滑塊輸入值乘以2.我可以保存val2對象,以便稍後可以在onRender()函數之外使用它? (我意識到我不需要使用onRender()函數在這個過分簡化的示例中創建val2對象,但我試圖保持示例簡單)。

謝謝你的任何建議!

library(plotly) 
library(htmlwidgets) 
library(shiny) 

myPlot <- qplot(data=mtcars, mpg, cyl) 
gMyPlot <- ggplotly(myPlot) 

ui <- shinyUI(fluidPage(
    sliderInput("ci", "Value:", min = 0, max = 1, value=0.95, step=0.01), 
    plotlyOutput("myTest") 
)) 

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

    ci <- reactive(input$ci) 

    output$myTest <- renderPlotly(gMyPlot %>% onRender(" 
        function(el, x, data) { 
        val2 = data * 2 
        console.log(val2) 
        }", data=ci()))}) 

shinyApp(ui, server) 
+0

任何反饋爲了我? –

+0

謝謝;很有幫助!它似乎正在解決我真正的問題(不僅僅是MWE),所以我現在不認爲我有任何編碼問題。作爲一個概念,當你注意到在服務器和客戶端之間來回傳遞值是低效的,你是否認爲這在某些情況下(大數據集等)尤其成問題?它似乎對我來說工作得非常快,但我很想知道是否可能存在某些應用程序,如果效率低下,它會開始危及性能?再次感謝你。 – luckButtered

+1

如果您將一個大型數據結構從shinyServer傳遞到客戶端的狹窄管道上,那肯定會成爲問題。但是如果你只是在個人電腦上使用它,或者只是在局域網上使用它,我不會擔心。 –

回答

1

這做到這一點。我修改了您的示例,使其稍微更具互動性。然後,我使用javascript存儲了「val2」值兩次,一次在h3標籤中(我首先工作),然後作爲反應列表的元素(當然這更有用)。請注意,由於值在服務器和客戶端之間來回切換,因此這看起來效率不高。

下面是代碼:

library(plotly) 
library(htmlwidgets) 
library(shiny) 

ui <- shinyUI(fluidPage(
    tags$h3('',class ='val2'), 
    sliderInput("ci", "Value:", min = 0, max = 34, value=34, step=1), 
    plotlyOutput("myPlot"), 
    textOutput("outval2") 
)) 

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

    ci <- reactive(input$ci) 

    output$myPlot <- renderPlotly({ 
      mdf <- mtcars %>% filter(mpg<ci()) 
      myPlot <- qplot(data=mdf, mpg, cyl) 
      ggplotly(myPlot) %>% onRender("function(el, x, data) { 
              val2 = data * 2 
              console.log(val2) 
              $('h3.val2').text('val2:'+val2); 
              Shiny.onInputChange('val2', val2); 
              }", data=ci()) 
      }) 
    output$outval2 <- renderPrint({sprintf("The calculated value is:%d",input$val2)}) 
    } 
) 
shinyApp(ui, server) 

這裏是工作程序的屏幕截圖:

enter image description here

一個培訓相關崗位值得一讀的是:Sending Shiny data from client to server

相關問題