본문 바로가기
R/shinyapps.io

local data로 shinyapp 만들어 올리기

by 거인과난쟁이 2020. 5. 6.

단순한 일이다. shinyapps.io 에 app을 만들어 올리는 설명에는 보통 빠져있지만, 모두가 거쳐야 하는 단계에 관한 것이다.

사용자는 자신의 데이터를 불러와서 작업하고, 그 결과(시각화, 테이블, 원자료 보여주기 등)를 shinyapps.io의 본인계정에 올리려고 할 것이다. 분명히 자신이 작업하는 컴퓨터 또는 온라인 rstudio (cloud)에서는 잘 작동하는데, shinyapps.io에 객체가 발견되지 않는다는 오류문을 분명히 본적이 있을 것이다.

최초의 데이터, 그러니까 객체로 만들기 이전에 불러와야 하는 데이터 파일이 함께 업로드되어야 한다. 그런데, 데이터 파일의 경로는 작업결과를 담는 디렉토리 내부에 함께 있어야 한다. 일반적으로 setwd()경로로 불러오면 오류가 난다. 반드시 app을 만드는 디렉토리 내부에 파일이 있어야 하며, 불러오기 명령은 긴 경로표시 없이 파일이름만 적어야 한다.

아래는 app.R로 저장된 스크립트이다:



library(shiny)
library(readxl)
예측_2020_소상공인_5월 <- read_excel("예측_2020.소상공인.monthly.xlsx", 5)
예측_2020_소상공인_6월 <- read_excel("예측_2020.소상공인.monthly.xlsx", 6)
# Define UI for data download app ----
ui <- fluidPage(
    
    # App title ----
    titlePanel("2020년 소상공인 월별 주요 이슈어"),
    
    # Sidebar layout with input and output definitions ----
    sidebarLayout(
        
        # Sidebar panel for inputs ----
        sidebarPanel(
            
            # Input: Choose dataset ----
            selectInput("dataset", "데이터셋 선택하기:",
                        choices = c("예측_2020_소상공인_5월", "예측_2020_소상공인_6월")),
            
            # Button
            downloadButton("downloadData", "내려받기")
            
        ),
        
        # Main panel for displaying outputs ----
        mainPanel(
            
            tableOutput("table")
            
        )
        
    )
)

# Define server logic to display and download selected file ----
server <- function(input, output) {
    
    # Reactive value for selected dataset ----
    datasetInput <- reactive({
        switch(input$dataset,
               "예측_2020_소상공인_5월" = 예측_2020_소상공인_5월,
               "예측_2020_소상공인_6월" = 예측_2020_소상공인_6월)
    })
    
    # Table of selected dataset ----
    output$table <- renderTable({
        datasetInput()
    })
    
    # Downloadable csv of selected dataset ----
    output$downloadData <- downloadHandler(
        filename = function() {
            paste(input$dataset, ".csv", sep = "")
        },
        content = function(file) {
            write.csv(datasetInput(), file, row.names = FALSE, fileEncoding="cp949")
        }
    )
    
}

# Create Shiny app ----
shinyApp(ui, server)