2018-10-25
閱讀量:
1007
R里的shiny包學(xué)習(xí)--shiny入門
Shiny是RStudio公司開發(fā)的新包,有了它,可以用R語言輕松開發(fā)交互式web應(yīng)用。
- 只用幾行代碼就可以構(gòu)建有用的web應(yīng)用程序—不需要用JavaScript。
- Shiny應(yīng)用程序會自動刷新計算結(jié)果,這與電子表格實(shí)時計算的效果類似。 當(dāng)用戶修改輸入時,輸出值自動更新,而不需要在瀏覽器中手動刷新。
- Shiny用戶界面可以用純R語言構(gòu)建,如果想更靈活,可以直接用HTML、CSS和JavaScript來寫。
- 可以在任何R環(huán)境中運(yùn)行(R命令行、Windows或Mac中的Rgui、ESS、StatET、RStudio等)
- 基于Twitter Bootstrap的默認(rèn)UI主題很吸引人。
- 高度定制化的滑動條小工具(slider widget),內(nèi)置了對動畫的支持。
- 預(yù)先構(gòu)建有輸出小工具,用來展示圖形、表格以及打印輸出R對象。
- 采用websockets包,做到瀏覽器和R之間快速雙向通信。
- 采用反應(yīng)式(reactive)編程模型,摒棄了繁雜的 事件處理代碼,這樣你可以集中精力于真正關(guān)心的代碼上。
- 開發(fā)和發(fā)布你自己的Shiny小工具,其他開發(fā)者也可以非常容易地將它加到自己的應(yīng)用中(即將面市?。?/li>
Shiny可以從CRAN獲取, 所以你可以用通常的方式來安裝,在R的命令行里輸入:
r install.packages("shiny")
Hello Shiny是個簡單的應(yīng)用程序, 這個程序可以生成正態(tài)分布的隨機(jī)數(shù),隨機(jī)數(shù)個數(shù)可以由用戶定義,并且繪制這些隨機(jī)數(shù)的直方圖. 要運(yùn)行這個例子,只需鍵入:
library(shiny)
runExample("01_hello")
Shiny應(yīng)用程序分為兩個部分:用戶界面定義和服務(wù)端腳本。這兩部分的源代碼將在下面列出。
在教程的后續(xù)章節(jié),我們將解釋代碼的細(xì)節(jié)并講解如何用“反應(yīng)性”表達(dá)式來生成輸出。現(xiàn)在,就嘗試運(yùn)行一下例子程序,瀏覽一下源代碼,以獲得對shiny的初始印象。也請認(rèn)真閱讀注釋。
用戶界面是在源文件ui.R中定義的:
library(shiny)
# Define UI for application that plots random distributions
shinyUI(pageWithSidebar(
# Application title
headerPanel("Hello Shiny!"),
# Sidebar with a slider input for number of observations
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min
=
0,
max
=
1000,
value
=
500)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
))
下面列出了服務(wù)端的代碼。從某種程度上說,它很簡單——生成給定個數(shù)的隨機(jī)變量, 然后將直方圖畫出來。不過,你也注意到了,返回圖形的函數(shù)被 renderPlot
包裹著。
library(shiny)
# Define server logic required to generate and plot a random distribution
shinyServer(function(input,
output)
{
# Expression that generates a plot of the distribution. The expression
# is wrapped in a call to renderPlot to indicate that:
#
# 1) It is "reactive" and therefore should be automatically
# re-executed when inputs change
# 2) Its output type is a plot
#
output$distPlot
<-
renderPlot({
# generate an rnorm distribution and plot it
dist
<-
rnorm(input$obs)
hist(dist)
})
})






評論(0)


暫無數(shù)據(jù)
推薦帖子
0條評論
0條評論
0條評論