텍스트 파일 업로드 (server)
사용자가 파일을 선택하면, 그 파일은 Shiny 앱을 실행하는 컴퓨터로 업로드되고 서버에서 사용할 수 있게 됩니다.
파일 입력의 input ID가 "myfile"이라면 업로드된 파일에 input$myfile로 바로 접근할 수 있을 것 같지만, 파일 입력은 그렇게 동작하지 않습니다. input$myfile은 선택한 파일에 대한 몇 가지 메타데이터를 담은 data.frame을 반환하며, 그중 가장 중요한 것은 datapath입니다. 파일 입력의 ID가 "myfile"이라고 가정하면, input$myfile$datapath는 파일이 위치한 경로가 됩니다.
업로드된 파일의 경로(예: C:\Users\Dean\AppData\Local\Temp\path\to\file.txt)를 얻은 후에는, 이 경로를 사용해 원하는 방식으로 파일을 읽을 수 있습니다. 업로드된 파일이 CSV라면 read.csv()를, 파일의 모든 행을 단순히 읽고 싶다면 readLines()를, 또는 파일 경로를 인수로 받는 다른 어떤 함수라도 사용할 수 있습니다.
이 연습은 강의의 일부입니다
사례 연구: R의 Shiny로 웹 애플리케이션 만들기
연습 안내
업로드한 파일의 텍스트를 워드 클라우드의 데이터 소스로 사용해 보세요. 구체적으로는 다음을 수행합니다.
- 업로드된 파일의 텍스트를 담을 반응형 변수
input_file을 정의하세요(19번째 줄).- 업로드된 파일의 경로를 사용해
readLines()함수로 파일의 텍스트를 읽어 오세요(24번째 줄).
- 업로드된 파일의 경로를 사용해
- 워드 클라우드 함수의
data매개변수에 반응형 변수input_file()을 사용하세요(29번째 줄).
파일 업로드를 테스트하려면, 컴퓨터에서 임의의 텍스트 파일을 만들어 앱에 업로드하셔도 됩니다. 또는 이 파일을 사용해 보셔도 됩니다(컴퓨터에 텍스트 파일로 저장). 그러면 Martin Luther King Jr.의 연설문인 I Have a Dream 텍스트로 워드 클라우드를 테스트할 수 있습니다.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
ui <- fluidPage(
h1("Word Cloud"),
sidebarLayout(
sidebarPanel(
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) {
# Define a reactive variable named `input_file`
input_file <- ___({
if (is.null(input$file)) {
return("")
}
# Read the text in the uploaded file
readLines(input$___$datapath)
})
output$cloud <- renderWordcloud2({
# Use the reactive variable as the word cloud data source
create_wordcloud(data = ___(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)