2018-10-26
閱讀量:
943
構建shiny應用程序之選項卡

示例程序Tabsets展示的是如何用選項卡(tabs)來組織輸出。要運行這個例子,就執(zhí)行下面的命令:
> library(shiny)
> runExample("06_tabsets")
選項卡面板(Tab Panels)
選項卡(tabsets)是由調用tabsetPanel
函數(shù)創(chuàng)建的,在這函數(shù)中,又需要用tabPanel
函數(shù)創(chuàng)建選項(tab)列表。每一個選項卡面板是由輸出元素組成的,這些元素在選項卡中垂直排列。
在這個例子中,我們修改了原來的Hello Shiny程序,增加了一個摘要和數(shù)據(jù)表,兩者分別渲染到它們各自的選項卡中。下面就是用戶接口的代碼:
library(shiny)
# Define UI for random distribution application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Tabsets"),
# Sidebar with controls to select the random distribution type
# and number of observations to generate. Note the use of the br()
# element to introduce extra vertical spacing
sidebarPanel(
radioButtons("dist",
"Distribution type:",
list("Normal"
=
"norm",
"Uniform"
=
"unif",
"Log-normal"
=
"lnorm",
"Exponential"
=
"exp")),
br(),
sliderInput("n",
"Number of observations:",
value
=
500,
min
=
1,
max
=
1000)
),
# Show a tabset that includes a plot, summary, and table view
# of the generated distribution
mainPanel(
tabsetPanel(
tabPanel("Plot",
plotOutput("plot")),
tabPanel("Summary",
verbatimTextOutput("summary")),
tabPanel("Table",
tableOutput("table"))
)
)
))
選項卡和反應式數(shù)據(jù)(Reactive Data)
將選項卡引入用戶接口的時候,應該強調為共享數(shù)據(jù)創(chuàng)建反應表達式的重要性。在這個例子中,每個選項卡都提供了對數(shù)據(jù)集的查看方式。如果對數(shù)據(jù)集的處理比較費時,那么用戶接口的定義可能變得很慢。下面的服務端腳本展示的是如何用反應表達式一次性計算數(shù)據(jù),其結果被三個選項卡所共享。
library(shiny)
# Define server logic for random distribution application
shinyServer(function(input,
output)
{
# Reactive expression to generate the requested distribution. This is
# called whenever the inputs change. The renderers defined
# below then all use the value computed from this expression
data
<-
reactive({
dist
<-
switch(input$dist,
norm
=
rnorm,
unif
=
runif,
lnorm
=
rlnorm,
exp
=
rexp,
rnorm)
dist(input$n)
})
# Generate a plot of the data. Also uses the inputs to build the
# plot label. Note that the dependencies on both the inputs and
# the 'data' reactive expression are both tracked, and all expressions
# are called in the sequence implied by the dependency graph
output$plot
<-
renderPlot({
dist
<-
input$dist
n
<-
input$n
hist(data(),
main=paste('r',
dist,
'(',
n,
')',
sep=''))
})
# Generate a summary of the data
output$summary
<-
renderPrint({
summary(data())
})
# Generate an HTML table view of the data
output$table
<-
renderTable({
data.frame(x=data())
})
})






評論(0)


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