如何使用{rlang}包从字符串动态创建变量名并赋值?
Hey there! I see you're trying to dynamically create a variable name from a string and assign a value to it using rlang—let's fix this up for you.
First, let's break down why your original attempt rlang::sym(x) <- 42 didn't work: rlang::sym(x) returns a symbol object, but the left-hand side of <- expects an actual variable name (not a symbol object). We need to either inject that symbol into the assignment or use a function that handles symbols directly for assignment.
Method 1: Use rlang::assign()
This is the most straightforward approach. The assign() function lets you specify the variable name (as a string or symbol) and assign a value to it in a specific environment:
library(rlang) # Your input string (generated programmatically) x <- "answer" # Assign the value to the variable named in x assign(x, 42, envir = current_env())
If you want to create the variable in the global environment specifically (instead of a function's local environment, for example), replace current_env() with global_env().
Method 2: Use Tidy Eval Injection (!!)
You can also use rlang's injection operator !! to convert the symbol into a valid variable name on the left-hand side of the assignment:
library(rlang) x <- "answer" var_symbol <- sym(x) # Inject the symbol into the assignment statement !!var_symbol <- 42
Verify It Works
After running either method, you can confirm the variable was created correctly:
> answer [1] 42
Quick Note on Best Practices
While dynamic variable creation has its use cases, it's often cleaner to store dynamic values in a list or named vector instead—this avoids cluttering your workspace and reduces the risk of accidental variable name collisions. But if you specifically need individual top-level variables, the methods above will get you there!
内容的提问来源于stack exchange,提问作者maia-sh

