如何使用 rlang 将字符串参数设置为 NULL(用于 facet 变量)?

How can you set string argument to NULL with rlang (for use in facet vars)?

我正在尝试使用 selectInput 为 ggplot 定义构面,因此 facet_grid 的输入是字符串或列名。其中一个选项是 "none"(不是其中一列) 如果未选中,下面的示例只要 "none" 就有效。我正在努力解决如何将 "none" 选项设置为 NULL 的问题。

我尝试了以下操作,但出现以下错误 "Error: cols must be NULL or a vars() specification"。

v <- ifelse(rfacet() == "none", NULL, vars(!!rlang::sym(rfacet())))  
# Module - facets options-------------------------------------------------------

   #UI
   plotOpt_rowfacet_UI <- function(id){
      ns <- NS(id)
      uiOutput(ns("ui_opt_rowfacet"))
   }

   #SERVER
   plotOpt_rowfacet <- function(input, output, session, facet_choices="none"){

        output$ui_opt_rowfacet <- renderUI({
         ns <- session$ns

         selectInput(inputId = ns("opt_rowfacet"), label = "Y-variable:",
          choices = facet_choices,
          selected = "none",
          multiple = FALSE, selectize = FALSE)
        })

        return(reactive(input$opt_rowfacet))  #returns column name as string
   }


library(shiny)
   library(dplyr)
   library(tidyverse)

ui <- fluidPage(

  plotOpt_rowfacet_UI("test1"),
  h4("facet selected ouput from module"),
  verbatimTextOutput("y_out"),
  plotOutput("plot")

)

server <- function(input, output, session){

  rfacet <- callModule(module=plotOpt_rowfacet, id="test1", facet_choices= c("none", "mpg", "disp"))

  output$y_out <- renderPrint({
    str(rfacet())
  })

  #this works except if none is selected
  #how can set to NULL if input="none"
  output$plot <- renderPlot({

    #v <- ifelse(rfacet() == "none", NULL, vars(!!rlang::sym(rfacet())))  

    p <- ggplot(mtcars, aes(x=wt, y=disp))+
        geom_point()+
        facet_grid(rows=vars(cyl), cols=vars(!!rlang::sym(rfacet())))
    print(p)
  })


}

shinyApp(ui, server)

你评论的v很接近, 你可以做类似下面的事情来定义 output$plot:

output$plot <- renderPlot({
  choice <- rfacet()
  v <- if (choice == "none") NULL else vars(!!rlang::sym(choice))

  ggplot(mtcars, aes(x=wt, y=disp)) +
    geom_point() +
    facet_grid(rows=vars(cyl), cols=v)
})

请注意 renderPlot 文档中的这条评论:

With ggplot2 graphics, the code in renderPlot should return a ggplot object; if instead the code prints the ggplot2 object with something like print(p), then the coordinates for interactive graphics will not be properly scaled to the data space.