将中间结果存储在管道中

时间:2019-02-28 14:30:40

标签: r magrittr

我想将中间结果存储在管道中,但是以某种方式与%>%管道运算符不兼容:

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

1 个答案:

答案 0 :(得分:2)

. %>%开头的管道链将建立功能序列,.的内容未评估。

如果使用(.) %>%,您将获得预期的行为。

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

reprex package(v0.2.1)于2019-03-02创建