【问题标题】:Select dynamically a dataframe subset动态选择数据框子集
【发布时间】:2021-10-20 11:31:52
【问题描述】:

我无法通过下拉菜单中选择的列动态地对数据框进行子集化。基本上,我想让用户决定哪一个将成为 y 轴上的列。

文件global.R

library(shiny)
library(plotly)

# Cars
data("USArrests")
USArrests$state <- row.names(USArrests)

文件ui.R

ui <- fluidPage(
    fluidRow(
        selectInput(inputId = "select_col",
                    label = tags$h4("Select Column"),
                    choices = c("Murder", "Assault", "UrbanPop", "Rape"),
                    selected = "Murder"
        ),
        plotlyOutput("plot")
    )
)

文件server.R

server <- function(input, output) {
    output$plot <- renderPlotly({
        plot_ly(USArrests, 
                x = ~state,
                y = ~input$select_col, # this works but is not reactive y = ~Murder
                type = 'bar')
        
    })   
}

最后一个文件是我遇到的问题。它不接受来自 select_col 下拉菜单 (y = ~input$select_col) 的值作为有效输入。

糟糕的解决方案

我想出了这个解决方案,可惜我不喜欢它。它太冗长了。有更有效的方法吗?

更正的服务器。R

server <- function(input, output) {
    output$plot <- renderPlotly({
        df <- USArrests[c('state', input$select_col)]
        names(df) <- c('state', 'to_y')
        plot_ly(df, 
                x = ~state,
                y = ~to_y, 
                type = 'bar')
        
    })   
}

【问题讨论】:

    标签: r dataframe shiny subset reactive


    【解决方案1】:

    一种选择是以编程方式生成公式:

    server <- function(input, output) {
        output$plot <- renderPlotly({
            plot_ly(USArrests, 
                    x = ~state,
                    y = formula(paste("~", input$select_col)),
                    type = 'bar')
            
        })   
    }
    

    【讨论】:

    • reformulate(input$select_col) 可能是另一种选择。
    • 代码高尔夫和简单,真的。不过,对于那些喜欢对代码进行过度基准测试并缩短 16 微秒的人,我相信 reformulate 会慢一些。 ;-) ...(不,我并不是因为基准测试而暗示我的更好,我不知道,但我很好奇)
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 2016-12-13
    • 2023-03-14
    • 2019-09-30
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多