Shiny Basic系列:

参考教程:https://mastering-shiny.org/

(1)IO控件

(2)Layout布局

(3)Reactive用法

(4)Feedback提醒

(5)Module模块

Shiny Package系列:

(1)shinyWidgets

(2)shinyJS

(3)shinydashboard

(4)shinydashboardPlus

(5)bslib

(6)Other pkgs


1. 基本形式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# module file

module_UI = function(id){
    ns <- NS(id)
    tagList(
        XXXInput(ns("var"),"label",...)
    )
}

module_Server = function(id){
    moduleServer(id, function(input, output, session){
        ns <- session$ns
        
        reactive({input$var})
        ...
    })
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# App.R

library(shiny)

source("module.R") #加载模块文件

ui <- fluidPage(
  histogramUI("hist1")  #使用模块的UI
)

server <- function(input, output, session) {
  histogramServer("hist1") #使用模块的server
}

shinyApp(ui, server)   

2. 其它参数

  • 定义模块的UI/Server时,均可以设置额外的参数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
module_UI = function(id, params = NULL){
    ns <- NS(id) 
    
    tagList(
        XXXInput(ns("var"),"label",...)
    )
}

## 对于module server函数的参数可以是普通值,也可以是reactive值
## 可结合stopifnot()检查是否为预期的类型

module_Server = function(id, param_A, param_B){
	stopifnot(is.reactive(data))
 	stopifnot(!is.reactive(filter))
    
    moduleServer(id, function(input, output, session){
        ns <- session$ns
        
        reactive({input$var})
        ...
    })
}

2. reactive返回值

  • 符合function()函数逻辑,默认返回最后一个语句对应的值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# 返回单个值
datasetServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    ......
    reactive(get(input$dataset, "package:datasets"))
  })
}

# 返回一个list所包括的多个值
datasetServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    ns <- session$ns
      
	......
    list(
      name = reactive(input$var),
      value = reactive(data()[[input$var]])
    )
  })
}
# res$name, res$value

3. 模块嵌套

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# module file
selectDataVarUI <- function(id) {
  ns <- NS(id)
    
  tagList(
    datasetInput(ns("data"), filter = is.data.frame), #嵌套模块-1
    selectVarInput(ns("var")) #嵌套模块-2
  )
}

selectDataVarServer <- function(id, filter = is.numeric) {
  moduleServer(id, function(input, output, session) {
    data <- datasetServer("data") #嵌套模块-1
    var <- selectVarServer("var", data, filter = filter) #嵌套模块-2
    var
  })
}