The ultimate goal in the question is to construct the following unevaluated call using r's computing on the language, where list
, a_name
and 50L
are provided from parameters.
list(a_name = 50L)
Which internally looks like
str(quote(list(a_name = 50L)))
# language list(a_name = 50L)
str(as.list(quote(list(a_name = 50L))))
#List of 2
# $ : symbol list
# $ a_name: int 50
I will put my variables in a list so the further code will be cleaner.
params = list(my_fun = as.name("list"), my_name = "a_name", my_value = 50L)
# What I tried so far?
# 1. The first thing that one would try
substitute(my_fun(my_name = my_value),
params)
#list(my_name = 50L) ## `my_name` was not substituted!
# 2. Workaround get the same output, but only after `setNames` call evaluation, so doesn't really answer the question about constructing specific call
substitute(setNames(my_fun(my_value), my_name), ## alternatively could be `structure(..., names=my_name)`
params)
#setNames(list(50L), "a_name")
# 3. Another workaround, not really computing on the language but parsing, and integer L suffix is gone!
with(expr = parse(text=paste0(my_fun, "(", my_name, " = ", my_value, ")"))[[1L]],
data = params)
#list(a_name = 50)
# 4. Working example using rlang
with(expr = rlang::call2(my_fun, !!my_name := my_value),
data = params)
#list(a_name = 50L)
Is there any way in base r to construct required call? Basically to get exactly same output as rlang
way but using base r.
Note that this Question is not a duplicate of this which was strictly asking for rlang
solution. This Question asks for a way to achieve it using base r. If there is no way to achieve it, I would like to know that as well. Thank you.
str2lang(paste("", "list", " (", "a_name", " = ", "50L", ")"))
give you what you want? – Merbrominstr2lang
is just special version ofparse
, so not any better than example 3. – Approver