gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:43:16 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com