rlang::sym in anonymous functions

后端 未结 1 1553
感动是毒
感动是毒 2020-12-17 10:51

I recently notices that rlang::sym doesn\'t seem to work in anonymous functions and I don\'t understand why. Here an example, it\'s pretty clumsy and ugly but I

相关标签:
1条回答
  • 2020-12-17 11:28

    The issue is not anonymous functions, but the operator precedence of !!. The help page for !! states that

    The !! operator unquotes its argument. It gets evaluated immediately in the surrounding context.

    This implies that when you write a complex NSE expression, such as select inside mutate, the unquoting will take place in the environment of the expression as a whole. As pointed out by @lionel, the unquoting then takes precedence over other things, such as creation of anonymous function environments.

    In your case the !! unquoting is done with respect to the outer mutate(), which then attempts to find column x1 inside d, not data. There are two possible solutions:

    1) Pull the expression involving !! into a standalone function (as you've done in your question):

    res1 <- d %>% mutate(tmp = map2(x, y, get_it))
    

    2) Replace !! with eval to delay expression evaluation:

    res2 <- d %>% mutate(tmp = map2(x, y, function(a, b){
      data %>%
        mutate(y1 = eval(rlang::sym(a))) %>%
        mutate(y2 = eval(rlang::sym(b))) %>%
        select(y1, y2, val)
    }))
    
    identical(res1, res2)       #TRUE
    
    0 讨论(0)
提交回复
热议问题