2015-08-21 186 views
-1

我正在嘗試爲班級寫一個Shiny應用程序,我正在教這個應用程序,從數據集中抽取一個隨機樣本並計算總結統計。每當我按下UI上的重置按鈕時,都應該對新子集進行採樣。這裏是我的代碼到目前爲止:R Shiny not randomizing

shinyServer(function(input, output) { 

# Output for Ch. 1 Problems: Central Tendency 

# Prepare data 
observeEvent(input$Ch1.Prob.CT.reset, { 
    Ch1.Prob.CT.n <- sample(8:12, 1) 
    Ch1.Prob.CT.obs <- sample(1:nrow(cars), Ch1.Prob.CT.n) 
}) 
data <- eventReactive(input$Ch1.Prob.CT.reset, { 
    cars[Ch1.Prob.CT.obs, 'dist', drop=F] 
}) 

# Outputs 
output$Ch1.Prob.CT.Data <- renderDataTable({ 
    data() 
}) 

output$Ch1.Prob.CT.Mean.out <- renderUI({ 
    if (is.na(input$Ch1.Prob.CT.Mean.in)) { # Error checking 
     p("No answer provided") 
    } else if (round(input$Ch1.Prob.CT.Mean.in, digits = 4) == round(mean(Ch1.Prob.CT.data[,1]), digits = 4)) { 
     p("Correct", style = "color:green") 
    } else { 
     p("Incorrect", style = "color:red") 
    } 
}) 
}) 

問題是,樣本不是隨機的;每次都是一樣的。即使按下重置按鈕,樣本也與之前的樣本完全相同。

爲什麼Shiny不隨機化?我怎樣才能使它再次隨機化?

+0

這是不建議使用s在閃閃發光的元素名稱(例如。使用'Ch1_Prob_CT_reset'而不是'Ch1.Prob.CT.reset') –

+0

此外,我很久沒有使用Shiny,所以我不太確定,但我會嘗試設置'Ch1.Prob.CT.obs 'data'無功元素中,* not *在觀察者中。如果你想在觀察者中更新它,你應該使用一個反應變量。 –

回答

0

這樣的代碼之前:

observeEvent(input$xxx, { 
x <- ... 
}) 
f <- eventReactive(input$xxx, { 
[do something with x] 
}) 

不起作用。

你可以簡單地刪除觀察,並做:

f <- eventReactive(input$xxx, { 
x <- ... 
[do something with x] 
}) 

如果你想使用一個變量加以修飾觀察員裏面,你必須使用一個反應列表,像這樣:

values <- reactiveValues() 
values$x <- [initial value of x] 
observeEvent(input$xxx, { 
values$x <- ... 
}) 

(另外,不要在閃亮元素的名稱使用的一些點(.)。)

0

添加一行如

set.seed(as.integer(Sys.time())) 

你需要的隨機數

+0

我認爲這與種子無關。問題僅僅是由於「重置按鈕」對輸出沒有影響。 –

+0

在示例命令之前,我在https://floatsd.shinyapps.io/GeoCUI/ demo頁面中添加了這一行(以數字形式),但似乎無法按預期工作。 – floatsd