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!

1
  • 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. Commented Sep 12, 2021 at 3:24

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.