如何使 R 程序(使用 Shiny)更加模块化

How to make R program (with Shiny) more modular

GitHub

上的完整 R 代码

我有允许人们绘制调色板的 R 代码,即

PaintPalette("GoldenTemple","GoldenTemple2") 

调用面向public的PaintPalette,然后调用面向内部的RenderPalette来绘制这个

但是,我有基于 shiny 的功能,允许用户 CherryPick 自己的调色板

CherryPickPalette("GoldenTemple","GoldenTemple2")

将推出 Shiny ....

但是渲染调色板的代码在闪亮的代码中重复了......如何简化这个?

CustomPal <- function(new_pal){

    #snip
    cherrypickedpalette <- runApp(list(
      ui = fluidPage(
        #snip
      ),
      server = function(input,output,session){
        outputdata <-  reactive({
          input$col
        })


        #snip

        output$cherrycolors=renderPlot({
          if (!is.null(input$col))
          {
            n <- length(input$col)
            old <- graphics::par(mar = c(0.5, 0.5, 0.5, 0.5))
            on.exit(graphics::par(old))
            graphics::image(1:n, 1, as.matrix(1:n), col = input$col,
                          ylab = "", xaxt = "n", yaxt = "n", bty = "n")
            graphics::rect(0, 0.9, n + 1, 1.1, col = grDevices::rgb(1, 1, 1, 0.8), border = NA)
            graphics::text((n + 1) / 2, 1, labels = "Cherry-Picked Palette", cex = 2, family = "serif")}
        }, height = 450, width = 450 ) 


       #snip
      }#end server
    )#end list
    )#end runApp
  }#end if interactive
}

看来您应该能够在 renderPlot() 中调用 RenderPalette() 函数来消除重复

 output$cherrycolors=renderPlot({
        if (!is.null(input$col)) {
            RenderPalette(input$col, "Cherry-Picked Palette")
        }}, height = 450, width = 450 )