4

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

Nacho Glez
  • 385
  • 3
  • 15
  • (Not trying to promote my own answers, it's just the one I knew of) Not exactly the same but the same underlying concept: https://stackoverflow.com/q/50257080/5325862 – camille Mar 03 '22 at 15:52
  • Hi @camille. I wish I had found that post before so I could use walk and not adding a new question. But, since I didn't know that walk was going to solve my issue, it was unlikely to find your answer. But, thanks for sharing it :) – Nacho Glez Mar 03 '22 at 16:40
  • You could mark yours as a duplicate of that one if you want, although on the surface the questions aren't the same. The `purrr` docs link to the [chapter](https://r4ds.had.co.nz/iteration.html#walk) of R for Data Science that goes through the `map` and `walk` families of functions – camille Mar 03 '22 at 16:45

1 Answers1

4

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.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • To get this to work as expected, I had to add an additional line break to the the final `cat` call, i.e. `cat('\n\n')` – nofunsally Jan 18 '23 at 16:56