04-25 20:26
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Data Mining with R] ShinyApps / Reactive Output에 대하여 본문

Data Science/Data Mining with R Programming

[Data Mining with R] ShinyApps / Reactive Output에 대하여

cinema4dr12 2014. 11. 2. 10:21

이번 글에서는 Reactive Output에 대하여 알아보기로 한다.

백번 글로 설명하기 보다는 한 번 예제로 설명하는 것이 효과적이기 때문에 동일한 application에 대하여 하나는 Reactive Output을 적용하지 않은 것과 다른 하나는 적용된 것을 비교하여 설명하기로 한다.

Application은 Slider Input으로부터 숫자를 입력받아 해당 숫자에 대한 Normal Distribution(N ~ (0,12))에 대한 랜덤 데이터를 생성하고 이들에 대한 Plot을 출력하는 것이다.



1. Without Reactive Output

[Results]

[ui.R]

shinyUI( pageWithSidebar( headerPanel("Reactive Example - Without Reactive Data"), sidebarPanel( sliderInput("N", "Number of Samples", min = 2, max = 1000, value = 100), actionButton("action", "Resample") ), mainPanel( tabsetPanel( tabPanel("Plot", plotOutput("plotSample")), id = "tabs1" ) ) ) )

[server.R]

shinyServer(function(input, output,session){ output$plotSample = renderPlot({ plot(rnorm(input$N)) }, height = 400, width = 400 ) })


결과를 보면 알 수 있듯이 Slider Input을 통해 값이 달라질 때마다 즉각적으로 새로운 Plot이 그려지는 것을 볼 수 있다. 사실 상 [Resample] 버튼의 역할은 없는 것이다.




2. With Reactive Output

[Results]

[ui.R]

shinyUI( pageWithSidebar( headerPanel("Example"), sidebarPanel( sliderInput("N", "Number of Samples", min = 2, max = 1000, value = 100), actionButton("action", "Resample") ), mainPanel( tabsetPanel( tabPanel("Plot", plotOutput("plotSample")), id = "tabs1" ) ) ) )

[server.R]

shinyServer(function(input, output,session){ Data = reactive({ input$action isolate({ return(rnorm(input$N)) }) }) output$plotSample = renderPlot({ plot(Data()) }, height = 400, width = 400 ) })

이번 결과에서는 Slider Input을 변경하더라도 Plot이 새로 그려지지 않는다. 반드시 [Resample] 버튼을 클릭해야 새로운 Plot이 그려진다.

비밀은 [server.R]의 빨갛게 표시한 부분이다. reactive 함수를 이용하여 actionButton이 클릭된 것(input$action)과 Slider Input 값(input$N)을 Data에 저장한 후 renderPlot 함수로 전달하는 것을 볼 수 있다.

이 때 중요한 것은, Slider Input에 대한 값은 reactive 함수 내에서 isolate 함수로 값이 전달되는 것이다. isolate 함수는 reactive 대상에서 제외된다는 것으로 실시간으로 값을 변경하지 않겠다는 뜻이다.

즉, Slider Input 값을 변경하더라도 [Resample] 버튼을 클릭하기 전까지는 새로운 Plot을 그리지 않겠다는 것이다.

Comments