R flexdashboard and shiny interactive plot

2019-08-27 15:54发布

问题:

I am learning flexdashboard, but I dont have clear the structure.

I have created a sample dataset to plot in a dashboard a barplot according to the selected variable.

The code is the next:

---
title: "flexdashboard: Shiny Embedding"
output: 
  flexdashboard::flex_dashboard:
    social: menu
    source_code: embed 
runtime: shiny
---

```{r global, include=FALSE}
library(tidyverse)
## generate a sample dataset
sample<-tbl_df(data.frame(c("City1","City2","City3","City1","City2","City3",
"City2","City3"),
c("A","B","C","D","D","A","A","B"),
c(12,14,15,12,12,14,8,10)))
colnames(sample)<-c("City","Country","Amount")
df<- 
reactive(sample%>%group_by(input$variable)%>%summarise(total=sum(Amount)))

```

Column {.sidebar}
-------------------------------------------
```{r}
selectInput(inputId="variable",label="group by",choices=c("City","Country"))
```

Column
------------------------------------------
### Plot

```{r}
renderPlot({barplot(total)})
```

But, I can´t get what I need.

Some suggestions or help?

回答1:

An easy option is to create a function with parameters instead of a reactive context:

makePlot <- function(groupBy) { #Instead of a reactive context
    data <- sample%>%group_by(groupBy)%>%summarise(total=sum(Amount))
    return(barplot(data[[groupBy]])) #Here we use a dynamic height using a variable name
}

And then call it from your renderPlot:

renderPlot(makePlot(input$variable))