构建应用

使用 R 构建 Shiny Web 应用

Kaelen Medeiros

Data Scientist

探索预期寿命与人均 GDP 的关系

一个应用,显示所选大洲和年份的人均 GDP 与预期寿命的交互式散点图

使用 R 构建 Shiny Web 应用

探索预期寿命与人均 GDP 的关系

一个应用,显示所选大洲和年份的预期寿命、人口和人均 GDP 的交互式表

使用 R 构建 Shiny Web 应用

构建 Shiny 应用:4 个步骤

  1. 添加输入(UI)
  2. 添加输出(UI/Server)
  3. 更新布局(UI)
  4. 更新输出(Server)
使用 R 构建 Shiny Web 应用

步骤 1:添加输入(UI)

ui <- fluidPage(
  titlePanel("Life Expectation vs. GDP Per Capita"),

selectInput('continent', 'Select Continent', unique(gapminder$continent)),
sliderInput('year', 'Select Year', 1952, 2007, 1990, step = 5) )
server <- function(input, output, session){ } shinyApp(ui = ui, server = server)
使用 R 构建 Shiny Web 应用

一个应用,显示选择大洲和年份的控件

使用 R 构建 Shiny Web 应用

步骤 2:添加输出(UI)

ui <- fluidPage(
  titlePanel("Life Expectation vs. GDP Per Capita"),
  selectInput('continent', 'Select Continent', unique(gapminder$continent)),
  sliderInput('year', 'Select Year', 1952, 2007, 1990, step = 5),

plotOutput('plot'), DT::DTOutput('table')
)
使用 R 构建 Shiny Web 应用

步骤 2:添加输出(Server)

server <- function(input, output, session){

output$plot <- renderPlot({ ggplot() })
output$table <- DT::renderDT({ gapminder })
}
使用 R 构建 Shiny Web 应用

一个应用,显示空白图和交互式表,以及选择大洲和年份的控件

使用 R 构建 Shiny Web 应用

步骤 3:更新布局(UI)

ui <- fluidPage(
  titlePanel("Life Expectation vs. GDP Per Capita"),

sidebarLayout(
sidebarPanel( selectInput('continent', 'Select Continent', unique(gapminder$continent)), sliderInput('year', 'Select Year', 1952, 2007, 1990, step = 5) ),
mainPanel( plotOutput('plot'), DT::DTOutput('table') )
) )
使用 R 构建 Shiny Web 应用

步骤 3:更新布局(UI)

ui <- fluidPage(
  titlePanel("Life Expectation vs. GDP Per Capita"),

sidebarLayout(
sidebarPanel( selectInput('continent', 'Select Continent', unique(gapminder$continent)), sliderInput('year', 'Select Year', 1952, 2007, 1990, step = 5) ),
mainPanel( tabsetPanel( tabPanel("Plot", plotOutput('plot')), tabPanel("Table", DT::DTOutput('table')) ) )
) )
使用 R 构建 Shiny Web 应用

一个应用,显示所选大洲和年份的预期寿命、人口和人均 GDP 的交互式表

使用 R 构建 Shiny Web 应用

步骤 4:更新输出(Server)

server <- function(input, output, session){
  output$plot <- renderPlot({

data <- gapminder %>% filter(year == input$year) %>% filter(continent == input$continent) print(data) ggplot(data, aes(x = gdpPercap, y = lifeExp)) + geom_point()
}) output$table <- DT::renderDT({
gapminder %>% filter(year == input$year) %>% filter(continent == input$continent) })
}
使用 R 构建 Shiny Web 应用

一个应用,在选项卡中显示所选大洲和年份的预期寿命与人均 GDP 的交互式散点图

使用 R 构建 Shiny Web 应用

Vamos praticar!

使用 R 构建 Shiny Web 应用

Preparing Video For Download...