Search code examples
rr-markdownflexdashboard

Dynamically switch to next tab in flexdashboard


I have around 20 sample for which I need to plot graphics such as histograms, boxplots, etc... I would like to organise all these plots in a flexdashboard where I would have one tab per sample. So each tab has one histogram, one boxplot, etc.

The below template produces only one tab. I doubled the dataset and add a column so it has two type, "first_sample" & "second_sample" (first chunk of code).

Is there an easy way to loop on these types so it generates the plots on seperated tabs for each sample ?

Thanks !

Edit : I also found this post but I couldn't make it work : Dynamicly increasing amount of tabs and pages in flexdashboards

---
title: "ggplotly geoms"
author: "Carson Sievert"
output: 
  flexdashboard::flex_dashboard:
  orientation: rows
social: menu
source_code: embed
---
  
```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
library(plyr)
library(flexdashboard)

# Make some noisily increasing data
set.seed(955)
dat1 <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

dat1$type <- "first_sample"

dat2 <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

dat2$type <- "second_sample"

dat <- rbind(dat1, dat2)

```

geom_point
=======================================================================
  
Row
-----------------------------------------------------------------------
  
### Scatter Chart with geom_point
  
```{r}
p <- ggplot(dat, aes(x=xvar, y=yvar)) +
  geom_point(shape=1)      # Use hollow circles
ggplotly(p)
```


### geom_smooth Linear Regression

```{r}
p <- ggplot(dat, aes(x=xvar, y=yvar)) +
  geom_point(shape=1) +    # Use hollow circles
  geom_smooth(method=lm)   # Add linear regression line
ggplotly(p)
```

Row
-----------------------------------------------------------------------
  
### geom_smooth with Loess Smoothed Fit
  
```{r}
p <- ggplot(dat, aes(x=xvar, y=yvar)) +
  geom_point(shape=1) +    # Use hollow circles
  geom_smooth()            # Add a loess smoothed fit curve with confidence region
ggplotly(p)
```

### Constraining Slope with stat_smooth

```{r}
n <- 20
x1 <- rnorm(n); x2 <- rnorm(n)
y1 <- 2 * x1 + rnorm(n)
y2 <- 3 * x2 + (2 + rnorm(n))
A <- as.factor(rep(c(1, 2), each = n))
df <- data.frame(x = c(x1, x2), y = c(y1, y2), A = A)
fm <- lm(y ~ x + A, data = df)

p <- ggplot(data = cbind(df, pred = predict(fm)), aes(x = x, y = y, color = A))
p <- p + geom_point() + geom_line(aes(y = pred))
ggplotly(p)

```

Solution

  • To do this I had to combine (and I am citing some of this post) :

    Use loop to generate section of text in rmarkdown

    • sprintf to prepare template text and name tabs by the types of data
    • results = "asis", rmarkdown chunk parameter "to prevent knitr from adding formatting to the output"
    • cat to prevent R from adding additional stuff like quotes and element numbers"
    • print to plot in for loops

    The following code produces a flexdashboard with two tabs and two plots for each sample in dat

    ---
    title: "test"
    author: "Paul Endymion"
    output: 
      flexdashboard::flex_dashboard:
      orientation: rows
    social: menu
    source_code: embed
    ---
    
      
    ```{r setup, include=FALSE}
    library(ggplot2)
    library(flexdashboard)
    library(data.table)
    
    # Make some noisily increasing data
    set.seed(955)
    dat1 <- data.frame(cond = rep(c("A", "B"), each=10),
                      xvar = 1:20 + rnorm(20,sd=3),
                      yvar = 1:20 + rnorm(20,sd=3))
    
    dat1$type <- "first_sample"
        
    dat2 <- data.frame(cond = rep(c("A", "B"), each=10),
                          xvar = 1:20 + rnorm(20,sd=3),
                          yvar = 1:20 + rnorm(20,sd=3))
        
    dat2$type <- "second_sample"
        
    dat <- rbind(dat1, dat2)
    
    setDT(dat)
    ```
    
    ```{r echo = FALSE, results = "asis"}
    
    template <- "
    
    %s
    =======================================================================
      
    ### Scatter Chart with geom_point
    
    " # dont't forget the newline
    
    template2 <- "
    
    Row
    -----------------------------------------------------------------------
    
    ### geom_smooth Linear Regression
    
    "
    
    for (i in unique(dat$type)) {
      cat(sprintf(template, i))
      
      p<-ggplot(dat[type == i], aes(x=xvar, y=yvar)) +
        geom_point(shape=1)      # Use hollow circles
      print(p)
      
      cat(template2)
      
      p2 <- ggplot(dat[type == i], aes(x=xvar, y=yvar)) +
      geom_point(shape=1) +    # Use hollow circles
      geom_smooth(method=lm)   # Add linear regression line
      print(p2)
    }
    ```
    

    It still needs tuning but it does what I wanted to do.