Search code examples
rmagrittr

saveRDS in a pipe %>% and have it return the object


Is there a way to use saveRDS in a pipe %>% chain?

c(1,2,3) %>% 
saveRDS(file="123.rda") %>% 
mean()

This currently gives an error because saveRDS returns null.

I want saveRDS() to return c(1,2,3)!


Solution

  • We can use the tee (%T>) operator from magrittr

    library(magrittr)
    1:3 %T>% 
       saveRDS(file="123.rda") %>%
       mean
    #[1] 2
    

    If we wants to return the same object, use I

    1:3 %T>% 
      saveRDS(file="123.rda") %>%
      I
    #[1] 1 2 3
    

    According to ?"%T>%"

    Pipe a value forward into a function- or call expression and return the original value instead of theresult. This is useful when an expression is used for its side-effect, say plotting or printing.