Creating tabs automatically in rmarkdown and plotting with purrr

Viewed 197

I am trying to do something similar to what is posted here.

In a automated way, creating tabs which each contains one plot. Using hchart I get the same results, but can replicate it using ggplot.

In this other post, they use ggplot instead, but they use a for-loop instead of purrr, but I try to add also cat('\n') at the end like it is mentioned here, but I still don't get the same results.

Iris test

cat('## Tabs panel {.tabset}   \n')
  iris %>% 
      dplyr::group_split(Species) %>% 
      purrr::imap(.,~{
        # create tabset for each group 
        cat('### Tab',.y,'   \n')
        p <- ggplot(.x, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
        print(p)
        cat('\n')
      })

This is the code that produces the closest output, but in the latest tab I get this annoying

[[1]] NULL [[2]] NULL [[3]] NULL

output which I am not able to remove.

enter image description here

Could anyone help me with this?

Thanks

1 Answers

Change the imap to iwalk

cat('## Tabs panel {.tabset}   \n')
  iris %>% 
      dplyr::group_split(Species) %>% 
      purrr::iwalk(.,~{
        # create tabset for each group 
        cat('### Tab',.y,'   \n')
        p <- ggplot(.x, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
        print(p)
        cat('\n')
      })

According to ?walk

walk() returns the input .x (invisibly). This makes it easy to use in pipe.

Related