R print() in pipe coerces wrong type

Viewed 35

when print() is used in a pipe it seems to be coercing x to the type of .

seq(1,10,1) %T>% print(x=summary(.)) %>% summary()

gives

Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  1       3       6       6       8      10 
Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
1.00    3.25    5.50    5.50    7.75   10.00 

What I initially wanted was to get sd() in addition to summary() and tried:

seq(1,10,1) %T>% print(x=sd(.)) %>% summary()

but got:

[1] 3
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    3.25    5.50    5.50    7.75   10.00 
> 

I tried variations with cat() and c() but the digits 1:10 go into the 1st dot of those functions.

The general question would be is there a way to use pipe operators to display multiple summaries or functions of what is moving through the pipe. I know I could have used one pipe ending in sd() and a 2nd pipe ending in summary() - but the beginning of my pipe is much more complicated than seq(1,10,1) and I wanted to avoid repeating or saving into an object.

1 Answers

Wrap it inside parentheses

library(magrittr)
seq(1,10,1) %T>% 
        {print(x=summary(.))} %>%
         summary
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    3.25    5.50    5.50    7.75   10.00 
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    3.25    5.50    5.50    7.75   10.00 

Or with the second case

seq(1,10,1) %T>% {print(x=sd(.))} %>% summary()
[1] 3.02765
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    3.25    5.50    5.50    7.75   10.00 
Related