想了解Shiny app运行原理,可以查看先前的文章一个 Shiny app的基本组成部分
Shiny app框架
简单来说,app.R的框架如下:
library(shiny)
# See above for the definitions of ui and server
ui <- ...
server <- ...
shinyApp(ui = ui, server = server)
- 首先需要调用shiny
- 编写ui和server
- 使用shinyApp()运行
Shiny app运行和调试
一个app最好存放在一个单独的文件夹,这样可以方便地调用;比如这儿我们创建一个文件夹为appname/
, 然后将编写的app.R
拷贝至文件夹appname/
,在R studio端使用runApp
运行
library(shiny)
runApp("app文件夹名")
runApp
来运行例子程序, 这个函数会启动shiny程序并打开浏览器以便查看程序。
在shiny程序运行的过程中,R控制台的交互将被阻断,也就是说,不能在控制台运行命令。
要停止shiny程序,你只需中断R,有两种方式:(1)在R的任何前端里按下Escape键;(2)点击R环境里提供的停止按钮。
在独立进程里运行
如果你不想在运行shiny程序的时候阻断访问控制台,则可以在单独的进程中运行shiny程序。你可以打开终端窗口或者控制台窗口,然后执行下面的命令:
R -e "shiny::runApp('./shinyapp')"
Shiny app 例子
安装的Shiny包中打包了一些例子可以直接运行
runExample("01_hello") # a histogram
runExample("02_text") # tables and data frames
runExample("03_reactivity") # a reactive expression
runExample("04_mpg") # global variables
runExample("05_sliders") # slider bars
runExample("06_tabsets") # tabbed panels
runExample("07_widgets") # help text and submit buttons
runExample("08_html") # Shiny app built from HTML
runExample("09_upload") # file upload wizard
runExample("10_download") # file download wizard
runExample("11_timer") # an automated timer
开始的时候,大家可以参考这些例子进行修改,编写一些简单的Shiny app;在[Github shiny-examples])(https://github.com/rstudio/shiny-examples)还有上百个例子,大家可以学习;
在Gallery中有发表的一些优秀app,大家也可以看看源码。
网友评论