maia-sh
maia-sh

Reputation: 641

Assign into variable from string

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

Upvotes: 0

Views: 56

Answers (1)

Lionel Henry
Lionel Henry

Reputation: 6803

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

Upvotes: 0

Related Questions