가장 간단하게 버튼을 두고 버튼을 클라이언트에서 누르게 되면 난수를 서버에서 생성하여 이를 textOutput 으로 찍어내는 웹앱을 작성해보자.
app.Rlibrary(shiny)
ui <- fluidPage(
actionButton(
"next_num",
"난수 생성을 위해 클릭하세요."
),
textOutput("rnorm_output")
)
server <- function(input, output, session) {
observeEvent(input$next_num, {
output$rnorm_output <- renderText({
rnorm(1)
})
})
}
shinyApp(ui, server)shiny 웹앱한단계 더 진화시켜 이를 모듈이 아닌 함수로 작성하여 보자. UI 부분은 random_UI 함수로, 서버는 random_server로 함수화 시켜 shiny 웹앱을 분리시켜 코드를 작성한다.
app.Rlibrary(shiny)
random_UI <- function() {
list(
actionButton(
"next_num",
"(함수) 난수 생성을 위해 클릭하세요."
),
textOutput("rnorm_output")
)
}
random_server <- function(input, output, session) {
observeEvent(input$next_num, {
output$rnorm_output <- renderText({
rnorm(1)
})
})
}
ui <- fluidPage(
random_UI()
)
server <- function(input, output, session) {
random_server(input, output, session)
}
shinyApp(ui, server)shiny 웹앱한단계 더 진화시켜 이를 모듈로 웹앱을 작성한다. 이를 위해 ns 네임스페이스를 도입한다. 즉, UI 모듈 부분에는 ns <- NS(id)을 추가시키고, 모듈 서버에는 moduleServer() 을 추가시킨다. 과거 callModule을 사용했으나 좀더 읽기 쉬운 코드로 새로 도입된 shiny 모듈 제작 방식을 적극 도입한다.
app.Rlibrary(shiny)
random_UI <- function(id) {
ns <- NS(id)
list(
actionButton(
ns("next_num"),
"(모듈) 난수 생성을 위해 클릭하세요."
),
textOutput(ns("rnorm_output"))
)
}
random_server <- function(id) {
moduleServer(id, function(input, output, session) {
observeEvent(input$next_num, {
output$rnorm_output <- renderText({
rnorm(1)
})
})
})
}
ui <- fluidPage(
random_UI("module_one")
)
server <- function(input, output, session) {
random_server("module_one")
# callModule(random_UI, "module_one")
}
shinyApp(ui, server)데이터 과학자 이광춘 저작
kwangchun.lee.7@gmail.com