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

时间:2018-06-20 20:13:00

标签: r shiny coding-efficiency

GitHub上的整个R代码

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

PaintPalette("GoldenTemple","GoldenTemple2") 

调用面向公众的PaintPalette,然后调用面向内部的RenderPalette进行绘制

enter image description here

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

CherryPickPalette("GoldenTemple","GoldenTemple2")

将启动Shiny ....

enter image description here

但是在闪亮的代码中重复了渲染调色板的代码……如何精简呢?

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
}

1 个答案:

答案 0 :(得分:1)

似乎您应该只需要在RenderPalette()内调用renderPlot()函数即可消除重复

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