You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用{rlang}包从字符串动态创建变量名并赋值?

How to Dynamically Create Variables with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:57:37