1

I am wondering how to tell R the string I used in the arguments of a function stands for a variable instead of the string itself. Specifically, I am dealing with 'Dict' package and run the following code as a trial.

library(Dict)
x  = c(1,2)

d = dict(x = 1)
d$keys
# 'x'

What I want is c(1,2) to be the key instead of 'x'. The same problem goes for 'list', for example

y = 'happy'
l = list(y = 1)

names(l)

The result would be 'y'. Moreover, one can solve this situation by names(l) <- y, but I don't think this is very efficient and clean.

Anyone has any idea how to do this in a one-line code? Thanks!

Lei Zhang
  • 13
  • 2
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 12 '21 at 03:24

1 Answers1

1

We could use setNames

out <- do.call(dict, setNames(rep(list(1), length(x)), x))
out$keys
[1] "1" "2"

Or we may use invoke or exec

library(purrr)
out <- invoke(dict, setNames(rep(1, length(x)), x))
out <- exec(dict, !!!setNames(rep(1, length(x)), x))

For the second case, also setNames works

setNames(list(1), y)
$happy
[1] 1

or we can use dplyr::lst

dplyr::lst(!! y := 1)
$happy
[1] 1
akrun
  • 874,273
  • 37
  • 540
  • 662