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

我正在尝试使用selectInput为ggplot定义构面,因此facet_grid的输入是字符串或列名。选项之一是“无”(不是列之一) 如果未选择,则下面的示例只要“ none”即可工作。我在如何设置将“ none”选项定义为NULL方面感到困惑。

我尝试了以下操作,但收到以下错误“错误:cols必须为NULLvars()规范”。

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,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",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)
mjguo8888 回答:如何使用rlang将字符串参数设置为NULL(用于facet vars)?

您注释掉的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文档中的这一评论:

  

对于ggplot2图形,renderPlot中的代码应返回一个ggplot对象;相反,如果代码使用类似print(p)的格式打印ggplot2对象,则交互式图形的坐标将无法正确缩放到数据空间。

本文链接:https://www.f2er.com/3087333.html

大家都在问