Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazy evaluation bug in mutate/transmute ? #5680

Closed
shahronak47 opened this issue Jan 6, 2021 · 1 comment
Closed

Lazy evaluation bug in mutate/transmute ? #5680

shahronak47 opened this issue Jan 6, 2021 · 1 comment

Comments

@shahronak47
Copy link

shahronak47 commented Jan 6, 2021

This is inspired from this SO post . I have made a smaller and simpler example.

Consider this data :

library(dplyr)
library(purrr)

data <- data.frame(i1 = 1:3, i2 = 3:1)
data
#    i1 i2
#1   1  3
#2   2  2
#3   3  1

Now let's say I want to add a new column temp to above dataframe which is going to be list of dataframes. I try :

data %>% mutate(t1 = map(i1, ~data %>% mutate(!!paste0('col', .x) := 1)))

This returns

Error in paste0("col", .x) : object '.x' not found

But it works if I use this without mutate :

map(data$i1, ~data %>% mutate(!!paste0('col', .x) := 1))

#[[1]]
#   i1 i2 col1
#1  1  3    1
#2  2  2    1
#3  3  1    1

#[[2]]
#  i1 i2 col2
#1  1  3    1
#2  2  2    1
#3  3  1    1

#[[3]]
#   i1 i2 col3
#1  1  3    1
#2  2  2    1
#3  3  1    1

It also works with mutate when we write a separate function to do the same thing.

fun_group <- function(i){
  data %>% mutate(!!paste0('col', i) := 1)
}

data %>% mutate(temp = map(i1, fun_group)) 

So why does 1 fail whereas 2 and 3 work fine. I have tried various modifications to the above to understand the reason but I failed to understand why it behaves differently. Tried changing data with mtcars, changing mutate with transmute but the error is still there.

@shahronak47 shahronak47 changed the title Lazy eval Lazy evaluation bug in mutate/transmute ? Jan 6, 2021
@lionel-
Copy link
Member

lionel- commented Jan 6, 2021

That's because !! injection happens eagerly by the outermost data masking function. This is tracked in r-lib/rlang#845. We'll fix this in the next major release of rlang if it's not too much of a breaking change (people might rely on this behaviour).

@lionel- lionel- closed this as completed Jan 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants