socialresearchcentre / projectable

Produce table-like objects made up of special metadata-rich column vectors, and project them into two dimensions.
https://socialresearchcentre.github.io/projectable
GNU General Public License v3.0
3 stars 0 forks source link

Consider wrapping `prj_tbl_*()` functions up in a single function #17

Open kinto-b opened 3 years ago

kinto-b commented 3 years ago

The main difficulty has to do with capturing the inputs.

I do not know of an easy way to turn a list of unquoted expressions passed through as the argument to a function into a list of quoted expressions. For instance, this doesn't work

prj_tbl_set <- function(.data, .rows, .cols) {
    .rows <- rlang::enexprs(.rows) 
    .cols <- rlang::enexprs(.cols)

    .data <- prj_tbl_rows(.data, !!!.rows)
    .data <- prj_tbl_cols(.data, !!!.cols)
    prj_tbl_summarise(.data)
}

Because rlang::enexprs(.rows) just captures the expression list(...) but we want a list of captured expressions.

The best alternative is to re-export rlang::exprs() as projectable::vars() or something and then have

prj_tbl_set <- function(.data, .rows, .cols) {
    .data <- prj_tbl_rows(.data, !!!.rows)
    .data <- prj_tbl_cols(.data, !!!.cols)
    prj_tbl_summarise(.data)
}

So the user writes

prj_tbl_set(
    mtcars, 
    vars(
        Cylinders = cyl, 
        Transmission = am
    ), 
    vars(
        `V-Shaped` = col_freq(n = vs %in% 1, N = vs %in% 0:1), 
        `Not V-shaped` = col_freq(n = vs %in% 0, N = vs %in% 0:1)
    )
)

The only thing I don't like about this is that it's inconsistent with the API of the other prj_tbl_*() functions where you pass through unquoted expressions. The equivalent to the above would be (using pipes)

mtcars %>%
  prj_tbl_rows(
    Cylinders = cyl, 
    Transmission = am
  ) %>%
  prj_tbl_cols(
     `V-Shaped` = col_freq(n = vs %in% 1, N = vs %in% 0:1), 
     `Not V-shaped` = col_freq(n = vs %in% 0, N = vs %in% 0:1)
  )