Search code examples
rmagrittr

store intermediary results in pipe


I want to store intermediary results in a pipe, but somehow this is not compatible with the %>% pipe operator:

if(!require(pacman)) install.packages('pacman')
pacman::p_load(dplyr, magrittr)

# generate test data
a <- 1:5 

# this works perfectly
b <- a %>% exp %T>%
  { a.mean <<- mean(sqrt(.)) } %T>%
  { a.sd <<- sd(sqrt(.)) } %>% 
  round(2) 

b

a.mean
a.sd

all.equal(a.mean, mean(sqrt(exp(a))))
all.equal(a.sd, sd(sqrt(exp(a))))    

# this not so much
b2 <- a %>% exp %T>%
  { a.mean2 <<- . %>% sqrt %>% mean } %T>%
  { a.sd2 <<- . %>% sqrt %>% sd } %>%
  round(2)

b2

a.mean2 # 'functional sequence
a.sd2   # 'functional sequence

Solution

  • Pipe chains starting with . %>% will build functional sequences, the content of . is not evaluated.

    If you use (.) %>% you'll get the behavior you expected.

    library(magrittr)
    a <- 1:5 
    
    b2 <- a %>% exp %T>%
    { a.mean2 <<- (.) %>% sqrt %>% mean } %T>%
    { a.sd2 <<- (.) %>% sqrt %>% sd } %>%
      round(2)
    
    b2
    #> [1]   2.72   7.39  20.09  54.60 148.41
    
    a.mean2 
    #> [1] 5.684048
    a.sd2
    #> [1] 4.232675
    

    Created on 2019-03-02 by the reprex package (v0.2.1)