r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
511 stars 138 forks source link

Do we need enlabel() and entext()? #303

Closed lionel- closed 3 years ago

lionel- commented 7 years ago

See discussion in #300.

lionel- commented 7 years ago

It seems like these should use rlang capture functions in order to support quasiquotation. But if we do so they won't work with forced arguments. Not sure what's best.

krlmlr commented 6 years ago

It would be great to have them, because enquo() and enexpr() don't work e.g. for S3 methods.

lionel- commented 6 years ago

Just added to 0.3.0 milestone so we don't forget.

krlmlr commented 6 years ago

Thanks. I think I'll use my hack for tibble, need to remove it once a better version becomes available in rlang.

lionel- commented 6 years ago

This should probably wait until 0.4.0 when we have figured out #636.

mjktfw commented 5 years ago

This comment will better fit #553 or #300., but since they're closed, I'll post here for anyone searching for similar solution. I'm storing references to large, but not computationally intensive objects/calls as quosures (along with its digest() and .Random.seed), and this obviously fails due to S3 dispatch. The workaround is to dispatch on quoted arguments.

require(tidyverse)
require(rlang)

dd <- tibble()

fn <- function(x) {
  ex <- eval_tidy(enquo(x))
  UseMethod('fn', ex)
}

fn.tbl_df <- function(x) {
  enquo(x)
}

fn(tibble())
#> <quosure>
#> expr: ^tibble()
#> env:  global
fn(dd)
#> <quosure>
#> expr: ^dd
#> env:  global

Created on 2019-02-06 by the reprex package (v0.2.0).

lionel- commented 5 years ago

Interesting, thanks for sharing!

lionel- commented 5 years ago
count_top <- function(df, variable, n = 5) {
  name <- enlabel(variable)
  df %>%
    mutate(temp = fct_lump(fct_infreq({{ variable }}), n = n)) %>%
    count(!!name := temp)
}

mtcars %>% count_top(as.factor(cyl))
#> # A tibble: 3 x 2
#>   `as.factor(cyl)`     n
#>   <fct>            <int>
#> 1 8                   14
#> 2 4                   11
#> 3 6                    7
lionel- commented 3 years ago

Closing this for now.