tidyverse / magrittr

Improve the readability of R code with the pipe
https://magrittr.tidyverse.org
Other
957 stars 157 forks source link

if `.` is modified when using `%T>%`, the main chain is affected #186

Closed moodymudskipper closed 4 years ago

moodymudskipper commented 5 years ago
mtcars %T>% {. <- iris; print(dim(.))} %>% head(2)
# [1] 150   5
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa

. might be used as a temp variable so this is not safe.

It could be solved by using local :

wrap_function <- function (body, pipe, env) 
{
    if (is_tee(pipe)) {
        body <- substitute({local(b); .}, list(b = body)) # instead of call("{", body, quote(.))
    }
    else if (is_dollar(pipe)) {
        body <- substitute(with(., b), list(b = body))
    }
    eval(call("function", as.pairlist(alist(. = )), body), env, 
        env)
}

Which would output :

mtcars %T>% {. <- iris; print(dim(.))} %>% head(2)
# [1] 150   5
#               mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
smbache commented 5 years ago

Good point

hadley commented 4 years ago

For now, I'd just say "don't do that"