【发布时间】: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