2017-10-11 7 views
0

私がしたいのは、forループ実行の出力をShiny Appの多くのレンダー出力で使用できるようにすることです。 問題の簡単な例を作成しました。 各renderPrint()関数には同じforループがあります。 forループをrender *()関数の外に移動するようにコードを記述できますか?Rシャイニー:多くのレンダリング*()関数で使用できるforループ出力

私はループで反応を使用する方法を例を見出しましたが、逆のタスクの解決策は見つかりませんでした。 ご協力いただきありがとうございます。

library(shiny) 

    ui <- fluidPage(sidebarLayout(
     sidebarPanel(
     numericInput(
      inputId = "seed", 
      label = "Set seed:", 
      value = 1 
     ), 
     numericInput(
      inputId = "Number", 
      label = "Number:", 
      value = 1, 
      min = 1, 
      step = 1 
     ) 
    ), 
     mainPanel(
     verbatimTextOutput("summary"), 
     dataTableOutput("table"), 
     verbatimTextOutput("data") 
    ) 
    )) 


    server <- function(input, output) { 
     a <- reactive({ 
     set.seed(input$seed) 
     rnorm(input$Number, 2, 1) 
     }) 

     b <- reactive({ 
     5 * a() 
     }) 

    rn <- reactive({ 
     c(1:input$Number) 
     }) 

     fun <- function(x, y) { 
     x + y 
     } 

     Table <- reactive({ 
     data.frame(rn = rn(), 
        a = a(), 
        b = b()) 
     }) 


     output$table <- renderDataTable({ 
     Table() 
     }) 
     output$summary <- renderPrint({ 
     for (i in Table()$rn) { 
      print (fun(Table()$a[i], Table()$b[i])) 
     } 
     }) 


     output$data <- renderPrint({ 
     for (i in Table()$rn) { 
      print (fun(Table()$a[i], Table()$b[i])) 
     } 
     }) 
    } 


    shinyApp(ui = ui, server = server) 

答えて

1

forループを関数に抽出します。リアクティブなコンテキスト(render*reactiveobserve)の外で関数を呼び出さない限り、問題のない関数ではリアクティブ値を使用できます。

例:

printTable <- function() { 
    for (i in Table()$rn) { 
    print (fun(Table()$a[i], Table()$b[i])) 
    } 
} 

output$summary <- renderPrint({ 
    printTable() 
}) 

output$data <- renderPrint({ 
    printTable() 
}) 

またはより効率的に、あなたは文字列として印刷出力をキャプチャして、ちょうどでき、それを再利用:

capturedTableString <- reactive({ 
    capture.output({ 
    for (i in Table()$rn) { 
     print (fun(Table()$a[i], Table()$b[i])) 
    } 
    }) 
}) 

printTable <- function() { 
    cat(capturedTableString(), sep = "\n") 
} 

output$summary <- renderPrint({ 
    printTable() 
}) 
関連する問題