R-Shiny Lesson01
Updated:
1. 개요
요즘 데이터를 시각화해야할 일 있어서 데이터 시각화 공부도 할 겸 R의 Shiny를 공부하고 블로그로 작성해보려 합니다.
디지털 뉴딜로 인해 데이터가 중요해지고 있어서 디지털 역량을 키우기 위해 데이터 시각화 중에서도 대시보드를 활용한 데이터 시각화를 진행합니다.
대시 보드는 특정 목표 또는 비즈니스 프로세스와 관련된 주요 성과 지료를 한 눈에 볼 수 있는 그래픽 사용자 인터페이스 유형입니다. - Wikipedia
즉, 대시보드는 데이터, 결과 분석을 한 눈에 볼 수 있도록 하는 것을 말합니다.
저는 R의 Shiny라는 package를 이용해서 대시보드를 만들어 보겠습니다.
이 포스트는 Shiny - Tutorial을 보고 만들었습니다.
2. Welcome to Shiny
Shiny는 R package로 interactive한 웹페이지를 쉽게 만들 수 있게 해줍니다. 먼저 R에서 Shiny package를 설치하고 shiny
package를 불러옵니다.
install.packages("shiny")
library(shiny)
# "01_hello" 예제 실행
runExample("01_hello")
shiny
페키지에는 총 11개의 예제를 가지고 있습니다. 더 많은 예시는 여기 사이트에서 볼 수 있습니다.
“01_hello” 예제
01_hello
예제는 R에서 제공하는 Faithful
dataset을 사용합니다. Faithful 데이터셋은 미국 와이오밍주, 엘로우스톤 국립공원에 있는 간헐온천(화산지대에 있는 물뿜는 것)이다. 아래 사진처럼!
Faithful Dataset 데이터셋 구성
dataframe 272행 2열로 구성되어 있다.
- eruptions - 분당 분출량(
인것 같다.(?)) - waiting - 다음 분출을 위한 대기 시간
3. Shiny 구성
Shiny는 가장 기본적인 app.R
R script를 가지고 있습니다.
app.R
script는 3가지로 구성됩니다.
- UI(User Interface) object
- server 함수
- UI object와 server 함수를 실행하는
ShinyApp
01_hello
예제 Rscript는 다음과 같습니다.
# app.R
library(shiny)
# Define UI for app that draws a histogram
ui <- fluidPage(
# App title
titlePanel("Hello Shiny!"),
# Sidebar layouto with input and output definitions
sidebarLayout(
# Sidebar panel for inputs
sidebarPanel(
# Input: Slider for the number of bins
sliderInput(inputId="bins",
label="Number of bins:",
min=1,
max=50,
value=30)
),
# Main panel for displaying outputs
mainPanel(
# Output: Histogram
plotOutput(outputId = "distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data
# with requested number of bins
# This expression that generates a histogram isi wrapped in a call
# to renderPlot to indicate that:
#
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks=bins, col="#75AADB", border="white",
xlab="Waiting time to next eruption (in mins)",
main="Histogram of waiting times")
})
}
shinyApp(ui=ui, server=server)
UI 는 Shiny 앱의 내용을 보여주는 역할합니다. Server는 input과 output을 이용하여 reactive
한 앱을 만들 수 있도록 해줍니다. shinyApp을 실행하면 sliderInput
으로 bins값을 수정할 수 있습니다. sliderInput값이 수정되면서 histogram이 바뀌는 것을 확인하실 수 있습니다.
runApp('app.R')
으로 Rscript를 실행할 수 있습니다. runApp()
은 display.mode
라는 인자가 있습니다. default값으로 normal
로 되어있습니다. display.mode
를 showcase
로 실행하면 app.R
의 스크립트까지 보여줄 수 있습니다.
runApp('app.R', display.mode='showcase')
실행그림
4. 마무리
이번 시간에는 Shiny 웹앱에 대해 배웠습니다. Shiny는 Web앱을 간편하게 만들게 해줍니다. Shiny에 대해 간단히 배웠지만, 더욱 공부한다면 데이터 시각화에 도움이 될 것 같습니다. Shiny를 더 배우면 ShinyDashBoard 보드를 사용하여 대시보드까지 만들 수도 있다고 합니다.
더 공부해서 대시보드도 만들어 보도록 하겠습니다! 감사합니다.
Comments