Shiny是RStudio公司开发的新包,有了它,可以用R语言轻松开发交互式web应用。
官方教程:https://shiny.rstudio.com/tutorial/
中文教程:http://yanping.me/shiny-tutorial/
英文教程:https://deanattali.com/blog/building-shiny-apps-tutorial/
Shiny是一个R包,使用它可以很容易构建交互式web应用程序。
1. 入门
Hello Shiny是个简单的应用程序, 这个程序可以生成正态分布的随机数,随机数个数可以由用户定义,并且绘制这些随机数的直方图。
library(shiny)
runExample("01_hello")
Shiny Text这个应用程序展示的是直接打印R对象,以及用HTML表格展示数据框。
更多示例:
"01_hello", "02_text", "03_reactivity", "04_mpg", "05_sliders", "06_tabsets", "07_widgets", "08_html", "09_upload", "10_download", "11_timer"
分别向我们演示了:
示例 | 输入形式 | 输出形式 |
01_hello # a histogram | 滑动条输入(sliderInput) | 图形输出(plotOutput) |
02_text # tables and data frames | 选择输入(selectInput) | 表格输出(tableOutput) |
03_reactivity# a reactive expression | 文本输入(textInput),数字输入(numericInput) | 反应式(标题h3) |
04_mpg # global variables | 复选框输入(checkboxInput) | |
05_sliders # slider bars | 滑动条输入 (数值类型、范围、步长、双取值、符号标示、动画) | |
06_tabsets # tabbed panels | 单选按钮(radioButtons) | 标签页(tabsetPanel) |
07_widgets # help text and submit buttons | 帮助信息(helpText),动作按钮(actionButton) | verbatimTextOutput |
08_html # Shiny app built from HTML | HTML样式 | |
09_upload # file upload wizard | 文件输入(fileInput) | |
10_download # file download wizard | | 文件输出(downloadButton) |
11_timer # an automated timer | | 时间输出 |
在shiny中使用反应值时,最常见的方式是使用input
对象。input
对象会被传递给shinyServer
函数中,让我们可以用类似列表的语法来访问网页上的输入值。为了将反应值转化为可以在网页上呈现的输出,我们要将它们赋值给output
对象(同样传递给shinyServer
函数)。
input values => R code => output values
创建:
2. 运行&调试
服务端脚本给两个输出赋值:output$caption
和output$mpgPlot
。为了让用户接口能显示输出,我们需要在主UI面板上添加相应的元素。
打印
cat("foo\n")
cat("bar\n", file=stderr())
调试浏览器
# Always stop execution here
browser()
# Stop execution when the user selects "am"
browser(expr = identical(input$variable, "am"))
错误处理器
# Immediately enter the browser when an error occurs
options(error = browser)
# Call the recover function when an error occurs
options(error = recover)
3. HTML元素
shiny function | HTML5 equivalent | creates |
|
| 段落 |
|
| 一级标题 |
|
| 二级标题 |
|
| 三级标题 |
|
| 四级标题 |
|
| 五级标题 |
|
| 六级标题 |
|
| 链接 |
|
| 换行 |
|
| 容器 |
|
| 内联文本 |
|
| 格式字体 |
|
| 代码块 |
|
| 图片 |
|
| 粗体 |
|
| 斜体 |
| | 直接将字符串作为HTML代码传递 |
使用HTML定义前端不需要ui.R文件,由index.html文件定义即可。
4. 输入
function | widget |
| Action Button |
| A group of check boxes |
| A single check box |
| A calendar to aid date selection |
| A pair of calendars for selecting a date range |
| A file upload control wizard |
| Help text that can be added to an input form |
| A field to enter numbers |
| A set of radio buttons |
| A box with choices to select from |
| A slider bar |
| A submit button |
| A field to enter text |
5. 输出
Output function | Creates |
| DataTable |
| raw HTML |
| image |
| plot |
| table |
| text |
| raw HTML |
| text |
6. 分享
- 通过R脚本;
- 通过网页。
7. 练习
日期计算器:https://dingdangsunny.shinyapps.io/DateCalculate
FFT分析:https://dingdangsunny.shinyapps.io/FastFourierTransform