Home > OS >  Is there a way to split piping in R to two output functions?
Is there a way to split piping in R to two output functions?

Time:12-03

I need to save latex and word versions of summary tables. Is there a pipe operator that can split the input into two outputs? Ideally I'd like something that will take species_tab and save into latex and word at the same time.

library(datasets)
library(flextable)
library(gt)

species_tab <- iris %>% 
  tabyl(Species)

species_tab %>% 
  gt() %>% 
  gtsave(filename = "species.tex")

species_tab %>% 
  flextable() %>% 
  save_as_docx(path = "species.docx")

CodePudding user response:

One option is to wrap with {}

library(datasets)
library(flextable)
library(gt)
iris %>% 
   tabyl(Species) %>% 
   {. %>%
    gt() %>% 
     gtsave(filename = "species.tex")
    . %>%
     flextable() %>%
     save_as_docx(path = "species.docx")
}

CodePudding user response:

You can use the %T>% operator from magrittr that is used when you want to return the lhs of the operator rather than the output of the rhs. However, it's messy and not really the use case for the operator, so would go with @akrun's solution. But there are cases where you don't have to use { } and the tee operator is preferable to the normal pipe.

library(magrittr)

species_tab %T>% 
  { gtsave(data = gt(.), filename = "species.tex")} %>% 
  flextable() %>% 
  save_as_docx(path = "species.docx")
  • Related