我有一个闪亮的应用程序,基本上遵循以下设置:
library(shiny)
weights <- data.frame("weights" = c(1, 2))
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("variable1",
"Weight 1",
min = 1,
max = 50,
value = weights[1,])
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 1]*input$variable1
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
但我有+100个不同的变量,所以实际上复制这段代码的每一行100次(像这样)似乎很麻烦:
x <- faithful[, 1]*input$variable1
y <- faithful[, 1]*input$variable2
z <- faithful[, 1]*input$variable3
xx <- x+y+z # I would plot xx
我是否缺少更优雅的解决方案?也许有反应功能?
答案 0 :(得分:0)
如评论所述,我建议如:
rowSums(sapply(1:100, function(var) faithful[, 1]*input[[paste0("variable", var)]]))
您可以在下面找到可重复的示例(带有2个输入):
library(shiny)
weights <- data.frame("weights" = c(1, 2))
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("variable1", "Weight 1",min = 1, max = 50, value = weights[1,]),
sliderInput("variable2", "Weight 2",min = 1, max = 50, value = weights[2,])
),
mainPanel(
plotOutput("distPlot")
)
)
)
server <- function(input, output) {
output$distPlot <- renderPlot({
data <- rowSums(sapply(1:2, function(var) faithful[, 1]*input[[paste0("variable", var)]]))
hist(data, col = 'darkgray', border = 'white')
})
}
shinyApp(ui = ui, server = server)