前言:
Shiny是一款R软件包,能够构建交互式Web应用,功能十分强大。官网地址:https://shiny.rstudio.com/
1.shiny包的安装
install.packages("shiny")
2.运行示例
shiny中内置了很多使用示例,可以直接运行:
library(shiny)#导入shiny包
runExample("01_hello")#运行内置示例"01_hello"
运行结果:3.Shiny apps的构成
Shiny apps包含一个R script即app.R,位于某个目录下如(newdir/),app可以通过函数runApp("newdir/app.R")运行。
app.R 包括三部分:
1.a user interface object
2.a server function
3.a call to the shinyApp function
即:1.用户界面(ui)object 控制应用程序的布局和外观。2.server function包含构建应用程序所需的说明。3.最后,shinyApp function通过ui和server创建Shiny应用程序对象。
4.自己构建交互程序
只要准备好app.R的三个部分,就是一个完整的交互式应用程序了,可以看下边的举例:
1)首先需要安装maps,mapproj包
install.packages(c("maps", "mapproj"))
2)数据下载
首先下载美国地图数据counties.rds,
然后下载帮助统计数据的脚本helpers.R
其次,将文件布置在文件夹中,命名为census-app
,在其中创建data
文件夹,将counties.rds文件放在里面,然后helpers.R放在census-app
目录下,如图:
3)创建app.R
将以下代码复制并粘贴到您的
census-app
目录下,新建一个app.R文件
# Load packages ----
library(shiny)
library(maps)
library(mapproj)
# Load data ----
counties <- readRDS("data/counties.rds")
# Source helper functions -----
source("helpers.R")
# User interface ----
ui <- fluidPage(
titlePanel("censusVis"),
sidebarLayout(
sidebarPanel(
helpText("Create demographic maps with
information from the 2010 US Census."),
selectInput("var",
label = "Choose a variable to display",
choices = c("Percent White", "Percent Black",
"Percent Hispanic", "Percent Asian"),
selected = "Percent White"),
sliderInput("range",
label = "Range of interest:",
min = 0, max = 100, value = c(0, 100))
),
mainPanel(plotOutput("map"))
)
)
# Server logic ----
server <- function(input, output) {
output$map <- renderPlot({
data <- switch(input$var,
"Percent White" = counties$white,
"Percent Black" = counties$black,
"Percent Hispanic" = counties$hispanic,
"Percent Asian" = counties$asian)
color <- switch(input$var,
"Percent White" = "darkgreen",
"Percent Black" = "black",
"Percent Hispanic" = "darkorange",
"Percent Asian" = "darkviolet")
legend <- switch(input$var,
"Percent White" = "% White",
"Percent Black" = "% Black",
"Percent Hispanic" = "% Hispanic",
"Percent Asian" = "% Asian")
percent_map(data, color, legend, input$range[1], input$range[2])
})
}
# Run app ----
shinyApp(ui, server)
保存app.R文件并运行runApp("census-app")
library(shiny)
runApp("census-app")
运行结果: