Crunch-io / rcrunch

R package for interacting with the Crunch API
https://crunch.io/r/crunch/
GNU Lesser General Public License v3.0
9 stars 15 forks source link

extract listing of variables from template in showMultitable #422

Open malecki opened 4 years ago

malecki commented 4 years ago

https://github.com/Crunch-io/rcrunch/blob/6ac94b43fe0bc4425d9f0ba261708211384da069/R/show.R#L341

malecki commented 4 years ago

This will extract the aliases you want in their order of appearance in the template, suitable for use in constructing other queries with their aliases or transcribing them to another multitable or dataset.


templateAliases <- function(x) {
    return(vapply(x@body$template, function(expr) {
    if ("each" %in% names(expr$query[[1]])) {
        # if the first element of the query is each, then this is
        # an array so take the second argument instead.
        exprToFormat <- expr$query[[2]]

        # if the second arg is a as_selected take the variable from
        # that to display var only
        if ((exprToFormat[["function"]] %||% "") == "as_selected") {
            exprToFormat <- exprToFormat$args[[1]]
        }

        return(crunch:::formatExpression(exprToFormat))
    }

    return(crunch:::formatExpression(expr$query[[1]]))
}, character(1)))

    }

m1 <- multitables(ds)[[1]]
templateAliases(m1)
variables(ds[templateAliases(m1)])```
gergness commented 4 years ago

I think we should (also?) have this as a variables method for Multitable objects:

I think ideally would return a variables catalog, but that would require getting to the variable catalog from a multitable, which I don't see how to do without url manipulation...

setMethod("variables", "Multitable", function(x) {
    variables(ds_from_multitable(x))[templateAliases(x)]
 })

ds_from_multitable <- function(mt) {
     loadDataset(sub("/multitables/.+", "", self(mt)))
}
malecki commented 4 years ago

Yeah that's why I went on the survey elsewhere — to get the aliases this should really be composed something more like aliases(template(mt)) — what we really need is a template accessor to start.