建立輸出物件
在 Shiny 中建立輸出有三個規則:
使用合適的
render*()函式建立物件。將 render 函式的結果存進 server 函式參數中的
output清單。更具體地,存進output$<outputId>,以取代 UI 中 ID 為outputId的輸出預留區。若輸出仰賴使用者修改過的輸入值,你可以使用 server 函式的
input參數存取任何輸入。更具體地,input$<inputId>會回傳 ID 為inputId的輸入欄位目前的值。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
這個 Shiny 應用的 UI 部分已可正常運作。你的任務是建立所有輸出。具體要求如下:
- 在 ID 為「cars_plot」的繪圖輸出預留區中,使用
cars資料集繪製圖形(第 23 行)。 - 在「greeting」文字輸出中,渲染問候文字,格式為「Hello NAME」,其中 NAME 為名稱輸入欄位的值(第 28 行)。
- 在「iris_table」輸出中,顯示
iris資料集前 n 列的表格,其中 n 來自數值輸入欄位的值(第 33 行)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Load the shiny package
library(shiny)
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("name", "What is your name?", "Dean"),
numericInput("num", "Number of flowers to show data for",
10, 1, nrow(iris))
),
mainPanel(
textOutput("greeting"),
plotOutput("cars_plot"),
tableOutput("iris_table")
)
)
)
# Define the server logic
server <- function(input, output) {
# Create a plot of the "cars" dataset
output$cars_plot <- render___({
plot(cars)
})
# Render a text greeting as "Hello "
output$greeting <- ___({
paste("Hello", ___)
})
# Show a table of the first n rows of the "iris" data
___ <- ___({
data <- iris[1:input$num, ]
data
})
}
# Run the application
shinyApp(ui = ui, server = server)