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