BACKGOUND: 你可以"问" RStudio生成示例R Markdown Shiny文档,其中包含此示例代码:
## Inputs and Outputs
You can embed Shiny inputs and outputs in your document.
Outputs are automatically updated whenever inputs
change. This demonstrates how a standard R plot can be
made interactive by wrapping it in the Shiny
`renderPlot` function. The `selectInput` and
`sliderInput` functions create the input widgets used to
drive the plot.
```{r, echo=FALSE}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
请注意,此示例不使用包含ui.R和server.R的文件夹。
问题: 如果你多次复制,第一个按预期工作,后面也会显示,但不会对输入参数的变化作出反应。
问题: 如何使用上面的多个嵌入式图创建一个R Markdown文档(不使用带有ui.R和server.R的外部文件夹),但确保每个都以交互方式工作?
答案 0 :(得分:3)
您必须为输入元素指定不同的ID,如下所示:
First embedded shiny plot :
```{r}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
Second embedded shiny plot :
```{r}
inputPanel(
selectInput("n_breaks2", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust2", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks2),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust2)
lines(dens, col = "blue")
})
```
答案 1 :(得分:3)
如RStudio Shiny Tutorial中所述,小部件功能的第一个参数是小部件名称,用于标识小部件。具有相同名称的多个小部件将不可用,这就是为什么简单地创建示例的两个副本不会创建两个工作副本。
要使其有效,您必须在每个inputPanel
调用中使窗口小部件名称唯一,然后在renderPlot
调用中使用此名称。