r - 使用 switch 从 ggplot2 函数中转换变量

标签 r ggplot2 shiny

我有一个 R Shiny 应用程序,它可以绘制 horsepower来自 mtcars针对用户选择的 x 变量的数据集。我希望用户能够在绘图之前选择要对 x 变量执行的转换。在下面的简化示例中,这些变换是将其平方或获得其倒数的能力。我正在使用开关功能来做到这一点。
虽然这个切换功能在非 Shiny 的上下文中工作,但我无法让它在一个工作 Shiny 的应用程序中执行。我知道我可以在数据框的 react 副本上执行转换并从中绘制,但如果可能的话,我想在 ggplot 调用本身中执行转换。有没有人对如何这样做有任何建议?

library(shiny)
library(tidyverse)

tran_func <- function(pred, trans) {
  switch(trans,
         "None" = pred,
         "Reciprocal" = 1/pred,
         "Squared" = pred^2,
  )
}

ui <- fluidPage(
  selectInput("xvar",
              "Select X Variable",
              choices = names(mtcars),
              selected = "disp"),
  selectInput("transform",
              "Select Transformation",
              choices = c("None", "Reciprocal", "Squared"),
              selected = "None"),
  plotOutput("scatter_good"),
  plotOutput("scatter_bad")
)

server <- function(input, output, session) {
  output$scatter_good <- renderPlot({
   mtcars %>% 
    ggplot(aes_string(x = "hp", y = input$xvar)) +
    geom_point()
  })
  output$scatter_bad <- renderPlot({
    mtcars %>% 
      ggplot(aes_string(x = "hp", y = tran_func(input$xvar, "Squared"))) +
      geom_point()
  })
}

shinyApp(ui, server)

最佳答案

问题是对从 input$xvar 传递的字符串的评估。修改列。一个选项是将“数据”也作为函数中的参数传递,并使用 [[在不转换为符号或评估的情况下对列进行子集化

library(shiny)
library(ggplot2)
library(dplyr)
tran_func <- function(data, pred, trans) {
  switch(trans,
         "None" = data[[pred]],
         "Reciprocal" = 1/data[[pred]],
         "Squared" = data[[pred]]^2,
  )
}

ui <- fluidPage(
  selectInput("xvar",
              "Select X Variable",
              choices = names(mtcars),
              selected = "disp"),
  selectInput("transform",
              "Select Transformation",
              choices = c("None", "Reciprocal", "Squared"),
              selected = "None"),
  plotOutput("scatter_good"),
  plotOutput("scatter_bad")
)

server <- function(input, output, session) {
  output$scatter_good <- renderPlot({
    mtcars %>%
      mutate(y_col = tran_func(cur_data(), input$xvar, input$transform)) %>%
      ggplot(aes(x = hp, y = y_col)) +
      geom_point()
  })
  
  output$scatter_bad <- renderPlot({
    mtcars %>% 
      mutate(y_col = tran_func(cur_data(), input$xvar, input$transform)) %>%
      ggplot(aes(x = hp, y =y_col)) +
      geom_point()
  })
  
}

shinyApp(ui, server)
-输出
enter image description here

关于r - 使用 switch 从 ggplot2 函数中转换变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64518664/

相关文章:

R Shiny : Keep/retain values of reactive inputs after modifying selection

R:创建稀疏模型矩阵的快速方法

r - 来自 dismo::gmap() 和 ggplot2 的谷歌地图

r - 用DT包输出时可以更改R默认表长度吗?

r - 如何使用 ggplot2 在单个单元格中绘制具有多个类别的热图?

r - 绘制 geom_point 和 geom_line

R Shiny : Reuse lengthy computation for different output controls

r - 查找相同值的每个子集的最大值

r - 在 shinydashboard 框内放置 markdown 压缩页面

R,变异和 "Unsupported type NILSXP for column"