ui 用戶自定義界面設(shè)置
server 服務(wù)端腳本
Shiny Text這個(gè)應(yīng)用程序展示的是直接打印R對(duì)象避凝,以及用HTML表格展示數(shù)據(jù)框。要運(yùn)行例子程序言秸,只需鍵入:
runExample("02_text")
前面那個(gè)例子里用一個(gè)滑動(dòng)條來(lái)輸入數(shù)值吟秩,并且輸出圖形仆百。而這個(gè)例子更進(jìn)了一步:有兩個(gè)輸入,以及兩種類型的文本輸出堵腹。
如果你改變觀測(cè)個(gè)數(shù)炸站, 將會(huì)發(fā)現(xiàn)Shiny應(yīng)用程序的一大特性:輸入和輸出是結(jié)合在一起的,并且“實(shí)時(shí)”更新運(yùn)算結(jié)果(就像Excel一樣)疚顷。 在這個(gè)例子中旱易,當(dāng)觀測(cè)個(gè)數(shù)發(fā)生變化時(shí),只有表格更新腿堤,而不需要重新加載整個(gè)頁(yè)面阀坏。
下面是用戶界面定義的代碼。請(qǐng)注意笆檀,"sidebarPanel" 和 "mainPanel" 的函數(shù)調(diào)用中有兩個(gè)參數(shù)(對(duì)應(yīng)于兩個(gè)"輸入" 和 兩個(gè) "輸出").
ui.R
library(shiny)
# Define UI for dataset viewer app ----
ui <- fluidPage(
# App title app標(biāo)題 ----
titlePanel("Shiny Text"),
# Sidebar layout with a input and output definitions 帶有輸入和輸出定義的邊欄布局----
sidebarLayout(
# Sidebar panel for inputs 用于輸入的側(cè)欄面板----
sidebarPanel(
# Input: Selector for choosing dataset ----
selectInput(inputId = "dataset",
label = "Choose a dataset:",
choices = c("rock", "pressure", "cars")),
# Input: Numeric entry for number of obs to view ----
numericInput(inputId = "obs",
label = "Number of observations to view:",
value = 10)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Verbatim text for data summary ----
verbatimTextOutput("summary"),
# Output: HTML table with requested number of observations ----
tableOutput("view")
)
)
)
服務(wù)端的程序要稍微復(fù)雜一點(diǎn)∪停現(xiàn)在,我們創(chuàng)建:
一個(gè)反應(yīng)性表達(dá)式來(lái)返回用戶選擇的相應(yīng)數(shù)據(jù)集误债。
還有兩個(gè)渲染表達(dá)式(rendering expressions,分別是renderPrint 和renderTable)妄迁,以返回 output$summary
的 output$view
的值寝蹈。
這些表達(dá)式和第一個(gè)例子中的 renderPlot 運(yùn)作方式類似:通過(guò)聲明渲染表達(dá)式,你也就告訴了shiny登淘,一旦渲染表達(dá)式所依賴的值(在這里例子中是兩個(gè)用戶輸入值的任意一個(gè):input$dataset
或 input$n
)發(fā)生改變箫老,表達(dá)式就會(huì)執(zhí)行。黔州。
# Define server logic to summarize and view selected dataset ----
server <- function(input, output) {
# Return the requested dataset ----
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars)
})
# Generate a summary of the dataset ----
output$summary <- renderPrint({
dataset <- datasetInput()
summary(dataset)
})
# Show the first "n" observations ----
output$view <- renderTable({
head(datasetInput(), n = input$obs)
})
}
Create Shiny app ----
shinyApp(ui = ui, server = server)