0Pricing
R Academy · 강의

코드 재사용을 위한 Shiny 모듈

UI와 서버 로직을 이름 공간이 지정된 재사용 가능한 모듈로 캡슐화합니다.

코드 재사용을 위한 Shiny 모듈은(는) CoddyKit의 무료 R Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 R Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

Shiny 모듈을 사용하는 이유

Shiny 앱이 커지면 모든 UI와 서버 코드를 하나의 파일에 두는 것은 관리하기 어려워집니다. 모듈은 자체적으로 완결된 Shiny UI와 서버 로직으로, 네임스페이스가 적용된 ID를 사용합니다. 하나의 앱에서 동일한 모듈을 여러 번 재사용해도 ID 충돌이 발생하지 않으며, 모듈을 독립적으로 테스트할 수도 있습니다.

# Problem: without modules, ID conflicts arise
# ui <- fluidPage(
#   selectInput('dataset', ...),  # used by plot1 AND plot2!
#   selectInput('dataset', ...)   # duplicate ID — BROKEN
# )

# With modules: each instance has its own namespaced IDs
# plotModule('plot1', ...)  ->  input$plot1-dataset
# plotModule('plot2', ...)  ->  input$plot2-dataset

NS() — 네임스페이스 함수

모든 모듈 UI 함수는 ns <- NS(id)로 시작합니다. Shiny에 전달하는 모든 UI 요소 ID는 ns()로 감싸야 합니다. 이렇게 하면 각 ID 앞에 id-가 붙어 네임스페이스가 생성되고, 모듈 인스턴스 간 충돌을 방지할 수 있습니다.

# Module UI function
filter_plot_ui <- function(id) {
  ns <- NS(id)  # create the namespace function

  tagList(
    selectInput(ns('dataset'), 'Choose Dataset:',
                choices = c('mtcars', 'iris', 'airquality')),
    sliderInput(ns('n_rows'), 'Rows to show:', 1, 50, 20),
    plotOutput(ns('scatter_plot'))
  )
}

moduleServer() — 서버 함수

moduleServer(id, function(input, output, session) {...})는 모듈 서버 로직을 정의하는 최신 방식(Shiny 1.5 이상)입니다. 함수 내부에서는 input, output, session에 네임스페이스가 자동으로 적용되므로 input$plot1-dataset이 아니라 input$dataset에 액세스합니다.

# Module server function
filter_plot_server <- function(id) {
  moduleServer(id, function(input, output, session) {

    data <- reactive({
      # input$dataset is already namespaced to this instance
      head(get(input$dataset), input$n_rows)
    })

    output$scatter_plot <- renderPlot({
      df <- data()
      plot(df[[1]], df[[2]],
           xlab = names(df)[1], ylab = names(df)[2])
    })
  })
}

앱에서 모듈 사용하기

ui에서 모듈 UI 함수를 호출하고 server에서 모듈 서버 함수를 호출하십시오. 두 함수에 동일한 id 문자열을 사용해야 합니다. 서로 다른 ID를 사용하여 동일한 모듈을 여러 번 호출하면 독립적인 인스턴스를 만들 수 있습니다.

# Main app using the module twice
ui <- fluidPage(
  h2('Plot 1'),
  filter_plot_ui('plot1'),   # instance 1
  hr(),
  h2('Plot 2'),
  filter_plot_ui('plot2')    # instance 2 — no ID conflicts!
)

server <- function(input, output, session) {
  filter_plot_server('plot1')  # wire up instance 1
  filter_plot_server('plot2')  # wire up instance 2
}

shinyApp(ui, server)

모듈 UI에 매개변수 전달하기

모듈 UI 함수는 일반적인 R 함수일 뿐입니다. 생성 시 각 인스턴스의 모양이나 동작을 사용자 지정하려면 id 외에 추가 매개변수를 지정하십시오. 이러한 매개변수는 UI를 만들 때 한 번 평가됩니다.

# Module UI with extra parameters
summary_table_ui <- function(id, title = 'Summary', height = '300px') {
  ns <- NS(id)
  tagList(
    h4(title),
    div(
      style = paste0('height:', height, '; overflow-y: auto;'),
      DTOutput(ns('tbl'))
    )
  )
}

# Use with custom titles
summary_table_ui('train_tbl', title = 'Training Data', height = '400px')
summary_table_ui('test_tbl',  title = 'Test Data',     height = '200px')

모듈에 반응형 값 전달하기

모듈 서버 함수는 반응형 값이나 표현식을 매개변수로 받을 수 있습니다. 이를 통해 부모 앱이 자식 모듈로 데이터를 전달할 수 있습니다. 모듈 내부에서는 반응형 값을 함수처럼 호출하여 현재 값을 가져옵니다.

# Module that accepts a reactive as input
chart_module_server <- function(id, data_reactive) {
  moduleServer(id, function(input, output, session) {
    output$chart <- renderPlot({
      df <- data_reactive()   # call the reactive passed in
      ggplot2::ggplot(df, ggplot2::aes(x = x, y = y)) +
        ggplot2::geom_point(colour = input$colour)
    })
  })
}

# In main server:
server <- function(input, output, session) {
  shared_data <- reactive({ load_data(input$source) })
  chart_module_server('chart1', data_reactive = shared_data)
  chart_module_server('chart2', data_reactive = shared_data)
}

모듈에서 반응형 값 반환하기

모듈 서버 함수는 부모에게 반응형 값을 반환할 수 있습니다. 이를 통해 자식 모듈이 부모와 통신할 수 있습니다. moduleServer()에서 반응형 값이나 반응형 값 목록을 반환하고, 부모 서버 함수에서 이를 저장하십시오.

# Module that returns a reactive to the parent
filter_module_server <- function(id, all_data) {
  moduleServer(id, function(input, output, session) {

    # Return the filtered data reactive
    filtered <- reactive({
      all_data[all_data$group == input$group_filter, ]
    })

    return(filtered)  # parent can use this reactive
  })
}

# In main server:
server <- function(input, output, session) {
  raw_data <- reactive({ read.csv('data.csv') })

  # filtered_data is a reactive returned from the module
  filtered_data <- filter_module_server('filter1', raw_data)

  output$main_plot <- renderPlot({ plot(filtered_data()) })
}

모듈 파일 구성

대규모 앱에서는 각 모듈을 R/ 폴더의 별도 파일에 배치하십시오. Shiny는 앱이 로드될 때 R/의 모든 파일을 자동으로 불러옵니다. 이렇게 하면 각 모듈이 자체적으로 완결되며 shinytest2 패키지를 사용해 독립적으로 테스트할 수 있습니다.

# Recommended project structure:
# myapp/
#   app.R                   # main app: source modules + wire up
#   R/
#     mod_filter_plot.R     # filter_plot_ui() + filter_plot_server()
#     mod_summary_table.R   # summary_table_ui() + summary_table_server()
#     mod_download.R        # download_ui() + download_server()
#   tests/
#     testthat/test-mod_filter_plot.R

# In app.R:
library(shiny)
# source('R/mod_filter_plot.R')  # not needed if in R/ folder
ui     <- fluidPage(filter_plot_ui('p1'))
server <- function(input, output, session) { filter_plot_server('p1') }
shinyApp(ui, server)

중첩 모듈

모듈 안에 다른 모듈을 포함할 수 있습니다. 부모 모듈은 session 인수를 사용하여 자체 session 네임스페이스를 자식 모듈 호출에 전달합니다. 중첩 단계마다 네임스페이스 접두사가 하나씩 추가됩니다: outer-inner-element_id.

# Outer module uses an inner module
outer_server <- function(id) {
  moduleServer(id, function(input, output, session) {

    # Call an inner module using this module's session
    inner_result <- inner_module_server(
      id      = 'inner',
      session = session  # passes the namespaced session
    )

    output$combined <- renderText({
      paste('Inner result:', inner_result())
    })
  })
}

# ID chain: outer -> inner
# Full ID: outer-inner-element

shinytest2로 모듈 테스트하기

shinytest2 패키지를 사용하면 모듈을 간단한 앱으로 감싸 자동화된 테스트를 작성할 수 있습니다. AppDriver로 브라우저를 조작하고, 입력을 설정하고, 출력 값을 검증할 수 있으며 실제 브라우저 세션은 필요하지 않습니다.

library(shinytest2)

# Wrap the module in a testable app
test_that('filter_plot module filters correctly', {
  test_app <- shinyApp(
    ui     = fluidPage(filter_plot_ui('test')),
    server = function(input, output, session) {
      filter_plot_server('test')
    }
  )

  app <- AppDriver$new(test_app)
  app$set_inputs('test-dataset' = 'iris')  # namespaced input
  app$wait_for_idle()

  # Assert plot was rendered
  expect_true(!is.null(app$get_value(output = 'test-scatter_plot')))
})

모듈 통신 패턴

모듈과 부모 앱 사이의 통신 패턴을 요약하면 다음과 같습니다:

  • 부모에서 모듈로: 반응형 값을 매개변수로 모듈 서버에 전달합니다.
  • 모듈에서 부모로: moduleServer()에서 반응형 값을 반환합니다.
  • 형제 모듈 사이: 부모가 공유 상태(reactiveValues)를 보관하고 각 모듈에 전달합니다.
  • 전역 상태: 부모에서 정의한 reactiveValues를 사용하고 참조를 아래로 전달합니다.
# Sibling module communication via parent state
server <- function(input, output, session) {
  shared <- reactiveValues(selected_row = NULL)

  # Table module sets the selection
  table_module_server('tbl', shared_state = shared)

  # Detail module reads the selection
  detail_module_server('detail', shared_state = shared)

  # Both modules communicate through 'shared' reactiveValues
  # Table sets shared$selected_row; Detail reads it
}

빠른 확인

모듈 UI 함수의 모든 UI 요소 ID를 ns()로 감싸야 하는 이유는 무엇입니까?

Shiny 모듈 복습

코드 재사용을 위한 Shiny 모듈의 핵심 내용:

  • 모듈은 NS(id)로 모든 ID에 네임스페이스를 적용하여 ID 충돌을 방지합니다.
  • 모듈 UI: ns <- NS(id)를 사용하는 일반 함수이며, 모든 ID를 ns()로 감쌉니다.
  • 모듈 서버: moduleServer(id, function(input, output, session) {...})입니다.
  • 반응형 값은 함수 매개변수로 모듈에 전달하고, 상위 방향으로 통신하려면 반응형 값을 반환합니다.
  • 서로 다른 ID로 동일한 모듈을 여러 번 호출하여 독립적인 인스턴스를 만듭니다.
  • 모듈을 R/mod_*.R 파일에 구성하면 Shiny가 R/ 폴더를 자동으로 불러옵니다.
  • shinytest2::AppDriver로 모듈을 테스트합니다.
# Complete module example
my_module_ui <- function(id) {
  ns <- NS(id)
  tagList(selectInput(ns('var'), 'Variable:', choices = names(mtcars)),
          plotOutput(ns('hist')))
}

my_module_server <- function(id, data) {
  moduleServer(id, function(input, output, session) {
    output$hist <- renderPlot(hist(data()[[input$var]]))
  })
}

# Use it:
ui <- fluidPage(my_module_ui('m1'), my_module_ui('m2'))
server <- function(input, output, session) {
  d <- reactive(mtcars)
  my_module_server('m1', d)
  my_module_server('m2', d)
}
shinyApp(ui, server)

자주 묻는 질문

“코드 재사용을 위한 Shiny 모듈” 강의는 무료인가요?

네 — “코드 재사용을 위한 Shiny 모듈” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 R Academy 강의 전체를 잠금 해제할 수 있습니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“코드 재사용을 위한 Shiny 모듈”에서 뭘 배우나요?

UI와 서버 로직을 이름 공간이 지정된 재사용 가능한 모듈로 캡슐화합니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

R Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 R Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“코드 재사용을 위한 Shiny 모듈” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 R Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 R Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 반응형 프로그래밍 심화
  2. 코드 재사용을 위한 Shiny 모듈
  3. renderUI와 insertUI를 활용한 동적 UI
  4. Shiny 앱 배포
← R Academy(으)로 돌아가기