gpt4 book ai didi

r - Shiny:输出元素/图的动态数量

转载 作者:行者123 更新时间:2023-12-02 15:44:44 29 4
gpt4 key购买 nike

我想制作一个响应式(Reactive)显示,根据选择的输入选择器的值显示不同数量的图。对于 mtcars 数据集,假设我想让用户在 Nr 之间进行选择。齿轮数或编号Carburatos 用于生成地 block 。

查看unique(mtcars$gear),我们看到它有4 3 5,所以有3个可能的值,而unique(mtcars$carb)4 1 2 3 6 8 因此有 6 个可能的值。因此,我想在 Nr. 时生成 6 个单独的图。化油器 被选择,并且当Nr. 时只有3 个图。 Gears 被选中。我玩过 conditionalPanel,但在我在选择器之间切换一两次后,它总是会崩溃。帮忙?

Shiny 的用户界面:

library(shiny)
library(googleVis)

shinyUI(bootstrapPage(
selectInput(inputId = "choosevar",
label = "Choose Cut Variable:",
choices = c("Nr. of Gears"="gear",
"Nr. of Carburators"="carb")),
htmlOutput('mydisplay') ##Obviously I'll want more than one of these...
# conditionalPanel(...)
))

Shiny 服务器:

shinyServer(function(input, output) {
#Toy output example for one out of 3 unique gear values:
output$mydisplay <- renderGvis({
gvisColumnChart(
mtcars[mtcars$gear==4,], xvar='hp', yvar='mpg'
)
})
})

最佳答案

灵感来自this ,你可以这样做:

ui.R

shinyUI(pageWithSidebar(            
headerPanel("Dynamic number of plots"),
sidebarPanel(
selectInput(inputId = "choosevar",
label = "Choose Cut Variable:",
choices = c("Nr. of Gears"="gear", "Nr. of Carburators"="carb"))
),
mainPanel(
# This is the dynamic UI for the plots
uiOutput("plots")
)
))

服务器.R

library(googleVis)
shinyServer(function(input, output) {
#dynamically create the right number of htmlOutput
output$plots <- renderUI({
plot_output_list <- lapply(unique(mtcars[,input$choosevar]), function(i) {
plotname <- paste0("plot", i)
htmlOutput(plotname)
})

tagList(plot_output_list)
})

# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.


for (i in 1:max(unique(mtcars[,"gear"]),unique(mtcars[,"carb"]))) {
local({
my_i <- i
plotname <- paste0("plot", my_i)

output[[plotname]] <- renderGvis({
data <- mtcars[mtcars[,input$choosevar]==my_i,]
if(dim(data)[1]>0){
gvisColumnChart(
data, xvar='hp', yvar='mpg'
)}
else NULL
})
})
}

})

它基本上动态创建 htmlOutput 图,并在子集中有数据时绑定(bind) googleVis 图。

关于r - Shiny:输出元素/图的动态数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31686773/

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