将中间结果存储在管道中
store intermediary results in pipe
我想将中间结果存储在管道中,但不知何故这与 %>%
管道运算符不兼容:
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
以. %>%
开头的管道链将构建功能序列,不评估.
的内容。
如果您使用 (.) %>%
,您将获得预期的行为。
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
我想将中间结果存储在管道中,但不知何故这与 %>%
管道运算符不兼容:
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
以. %>%
开头的管道链将构建功能序列,不评估.
的内容。
如果您使用 (.) %>%
,您将获得预期的行为。
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