【问题标题】:Save object created in onRender() function in htmlWidgets在 htmlWidgets 中保存在 onRender() 函数中创建的对象
【发布时间】:2017-03-25 16:54:01
【问题描述】:

我在 Shiny 应用程序中使用 htmlWidgets 包中的 onRender() 函数。我正在尝试保存我在给定的 onRender() 函数调用中创建的某些对象,以便它们可以在给定的 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)

【问题讨论】:

  • 对我有什么反馈吗?
  • 谢谢;很有帮助!它似乎正在解决我的真正问题(不仅仅是 MWE),所以我认为我现在没有任何编码问题。作为一个概念,当您注意到在服务器和客户端之间来回传递值是低效的,您是否认为这在某些情况下(大型数据集等)特别成问题?它对我来说似乎工作得很快,但我很想知道是否有某些应用程序效率如此之低以至于会开始危及性能?再次感谢您。
  • 如果你通过一个狭窄的管道从你的 shinyServer 传递一个大的数据结构到你的客户端,那肯定是个问题。但是,如果您只是在 PC 上使用它,甚至只是通过 LAN,我不会担心。

标签: javascript r shiny plotly htmlwidgets


【解决方案1】:

这样做。我修改了您的示例,使其更具交互性。然后我使用 javascript 将“val2”值存储两次,一次在 h3 标记中(我首先开始工作),然后作为反应性input 列表的元素(当然这更有用)。请注意,这似乎不是很有效,因为值在服务器和客户端之间来回传递。

代码如下:

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)

这是工作应用的屏幕截图:

值得一读的相关帖子是:Sending Shiny data from client to server

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多