데이터 소스 선택하기(서버)
라디오 버튼을 사용할 때, 서버에서 해당 값에 접근하면서 조건문(if-else)이 필요할 때가 있습니다. 선택에 따라 수행할 작업이 달라지고, 진행 방법을 결정하기 전에 선택된 값을 확인해야 하기 때문입니다.
예를 들어, 데이터 소스를 선택하는 라디오 버튼의 경우 어떤 선택지가 활성화되었는지에 따라 실행해야 하는 코드가 달라집니다.
다음 작업은 사용자가 고른 라디오 버튼에 따라 워드 클라우드 함수에 적절한 데이터 소스를 적용하는 것입니다.
이 연습은 강의의 일부입니다
사례 연구: R의 Shiny로 웹 애플리케이션 만들기
연습 안내
- 워드 클라우드에 사용할 데이터를 담을 반응형 변수
data_source를 정의하세요(28행). - "book" 옵션("Art of War")이 선택되면
artofwar책을 데이터 소스로 지정하세요. "own" 옵션("Use your own words")이 선택되면 텍스트 영역의 값을 데이터 소스로 지정하세요. "file" 옵션("Upload a file")이 선택되면 사용자가 업로드한 파일에서 읽은 텍스트를 데이터 소스로 지정하세요(33–36행). data_source()반응형 변수를 워드 클라우드 함수의data인수로 사용하세요(51행).
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
ui <- fluidPage(
h1("Word Cloud"),
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "source",
label = "Word source",
choices = c(
"Art of War" = "book",
"Use your own words" = "own",
"Upload a file" = "file"
)
),
textAreaInput("text", "Enter text", rows = 7),
fileInput("file", "Select a file"),
numericInput("num", "Maximum number of words",
value = 100, min = 5),
colourInput("col", "Background color", value = "white")
),
mainPanel(
wordcloud2Output("cloud")
)
)
)
server <- function(input, output) {
# Create a "data_source" reactive variable
data_source <- ___({
# Return the appropriate data source depending on
# the chosen radio button
if (input$source == "book") {
data <- artofwar
} else if (input$source == ___) {
data <- input$___
} else if (___ == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
# Use the data_source reactive variable as the data
# in the word cloud function
create_wordcloud(data = ___(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)