0

I would like to dynamically create a variable name from a string and then assign in a value. I believe I should be able to easily do this with {rlang} but haven't been able to work it out from package docs, Advanced R, and searching. Below is a pseudo-reprex of what I'm looking for. Thank you for your guidance!

My desired output: answer <- 42

My input: x <- "answer" (except that "answer" is generated and not hardcoded in the script)

Attempt: rlang::sym(x) <- 42

maia-sh
  • 537
  • 4
  • 14
  • 4
    `assign(x, 42)`? If you need this, your whole approach is bad practice and should be changed. – Roland Aug 30 '21 at 12:22
  • I think this is the relevant duplicate https://stackoverflow.com/questions/6034655/convert-string-to-a-variable-name – Ronak Shah Aug 30 '21 at 12:26

1 Answers1

0

Is answer <- 42 your desired output, or your desired effect?

If it's the desired output, inject the answer symbol in a defused expression with expr()

expr(!!sym(x) <- 42)
#> answer <- 42

answer
#> Error: object 'answer' not found

If you need to evaluate this expression, use inject():

inject(!!sym(x) <- 42)

answer
#> [1] 42
Lionel Henry
  • 6,652
  • 27
  • 33