2017-10-28 27 views
1

私は簡単な練習をしています:xはdata.frameの列です。私はxの平均をプリントアウトするシャイニーアプリを作りたいと思う。 「2倍する」チェックボックスが選択されている場合は、xに2を掛けます。そうでない場合は、古い値を使用します。変数をグローバルに変更しないでください

library(shiny) 
dt <- data.frame(x = 1:10, y = rep(c(2,3),5)) 

ui <- fluidPage(
    checkboxInput("myCheckbox", "multiple dt$x by 2"), 
    actionButton("myButton", "show result") 
) 

server <- function(input, output) { 
    i <- 0 

    observeEvent(input$myCheckbox,{ # if this checkbox is true then dt$x should be muiltiplied by 2 
    i <<- i + 1 
    if(i > 1){ # first call should not change dt$x 
     if(input$myCheckbox){ 
     dt$x <<- dt$x * 2 
     }else{ 
     dt$x <<- dt$x/2 
     } 
    } 
    }) 

    observeEvent(input$myButton,{ 
    showNotification(paste0("Mean of dt$x is equal ", mean(dt$x)), type="default") 
    }) 
} 

shinyApp(ui, server) 

<<-を避けるにはどうすればよいですか?それは危険で、300行のコードを持つもっと大きなShinyアプリでは、Rがスコープを選択できないというエラーが表示されることがあります。

+0

'dt $ x'に何度も乗算したいのですか?または2倍して元の値に戻すかどうかを切り替えるだけですか? –

+0

を切り替えます。私のコードで見ているように。 –

答えて

1

あなたは反応性プログラミングにreactiveValues機能を使用することができます。

library(shiny) 
dt <- data.frame(x = 1:10, y = rep(c(2, 3), 5)) 

ui <- fluidPage(
    checkboxInput("myCheckbox", "multiple dt$x by 2"), 
    actionButton("myButton", "show result") 
) 

server <- function(input, output) { 
    values <- reactiveValues(x = dt$x) 
    observeEvent(input$myCheckbox, { 
    if (input$myCheckbox) { 
     values$x <- values$x * 2 
    } else { 
     values$x <- values$x/2 
    } 
    }) 
    observeEvent(input$myButton, { 
    showNotification(paste0("Mean of dt$x is equal ", mean(values$x)), type = "default") 
    print(dt$x) 
    }) 
} 

shinyApp(ui, server) 

reactiveValues機能が無効な値を格納するためのオブジェクトを返します。変数をグローバルに変更するのを避けることができます。

1

は、サーバー機能でdtというリアクティブバージョンを定義します。複数の入力値を使用して、反応式を定義することができます。別のオプションは、reactiveValues()オブジェクトを設定してオブザーバーで更新することですが、reactive()という表現がこの場合に適していると思います。定義しようとしている値が現在の入力値によって完全に決定されている場合。アプリで繰り返し操作したい場合は、reactiveValues()が良いかもしれません。

library(shiny) 
library(dplyr) 
dt <- data.frame(x = 1:10, y = rep(c(2,3),5)) 


ui <- fluidPage(
    checkboxInput("myCheckbox", "multiple dt$x by 2"), 
    checkboxInput("myOtherCheckbox", "set dt$x to 0"), 
    actionButton("myButton", "show result") 
) 


server <- function(input, output){ 
    dt2 <- reactive({ 
    mutate(dt, x = if(input$myCheckbox==TRUE){2*x} else{x}) %>% 
    mutate(x = if(input$myOtherCheckbox==TRUE){0}else{x} 
    }) 

    observeEvent(input$myButton,{ 
    showNotification(paste0("Mean of dt$x is equal ", mean(dt2()$x)), type="default") 
    }) 
} 


shinyApp(ui, server) 
+0

しかし、多くのボタンでdt $ xを何度も再配置したいのですが? 'dt2 < - reactive({ if(input $ myCheckbox2 == TRUE){mutate(dt、x = 0)} else {dt} })' –

+0

のように同じxに2番目の反応性を追加したい場合はどうすればいいですか?おそらくそれをすべて同じ反応的な表現に入れます。複数の入力値に基づいて定義することができます –

関連する問題