Creating quoted strings (automatically) / use metaprogramming in fcase

Creating quoted strings (symbols) automatically

Problem

Is there a way to make this more concise?

grp_list <- tribble(~grp, ~grp_quoted,
                    50L, quote(grp_50))

For example, just passing a vector of group numbers and then converting them to symbols/quoting along these lines (doesnt work).

tribble(~grp,
                 50L,
                 80L) %>% 
mutate(grp_name= glue("grp_{grp}"),
                grp_quoted = quote(grp_name))

--> Error : grp_name` must be a vector, not a symbol

Is there a way to construct the string (e.g. grp_50) and then turn it into a symbol(vector)?

Setup/Usage

I have a script that queries, transforms and reports data based on groups. The script and functions are directed by two group selectors: The group nr, e.g. 50 and by the extended group name, e.g. grp_50. The name is required to select and query the data as well as to do a logical test in an fcase construction in dat.table.

dt_lag <- partial(shift, type = "lag", n = 1L)

grp_dt[,
       `:=`(grp_new = fcase((eval(params$grp_quoted) == 1 &
                               dt_lag(eval(params$grp_quoted)) == 0 &
                               dt_lag(vt_datayear) == 366), 1L,
                            default = 0L),
            grp_new_vper = fcase(eval(params$grp_quoted) == 1 &
                                   dt_lag(eval(params$grp_quoted)) == 0 &
                                   dt_lag(vt_datayear) == 366 &
                                   vt_datayear == 365, 1L,
                                 default = 0L)
       ),
       by = id]

The key point is that I need the data.table/dt_lag construction to be so generic that it works across all possible group names (grp_1 to grp_inf). I got it working by first quoting params$grp_quoted <- quote(grp_50)and then evaluating it within fcase(eval(params$grp_quoted) == 1).

I couldn't get it to work in fcase in any other form but I would be happy for any suggestion how it might be done better.

Thanks

Could you make the example reproducible, so that the code can be copy-pasted and run as is?

I've only looked at your problem statement and not at setup/usage which I don't think you've provided in a way inviting support, but hopefully this will get you on your way.

(grp_list2 <- tribble(~grp,
        50L,
        80L) %>% 
  mutate(grp_name= glue("grp_{grp}"),
         grp_quoted = rlang::parse_exprs(grp_name)))
1 Like

Thanks, that indeed does get me on the way.

In the meantime i worked out a solution that doesn't require the extra step of quoting the grp_name. Using get within fcase works.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.