[英]How to assign a variable values stored in a vector to a series of variable names stored in a character vector in R?
I am trying to determine how to assign variable a values stored in a vector to a series of variable names stored in a character vector in R?我正在尝试确定如何将存储在向量中的变量值分配给存储在 R 中字符向量中的一系列变量名称?
Here is a toy example of what I'm trying to do: I would like to have ultimately have the values 1, 2, and 3, stored in the variables A, B, and C respectively, so that print(A)
returns 1
, print(B
) returns 2
, etc. However, I would like to store the variables A, B, and C
as character values in a vector called my_variables .这是我正在尝试做的一个玩具示例:我希望最终将值 1、2 和 3 分别存储在变量 A、B 和 C 中,以便
print(A)
返回1
、 print(B
) 返回2
等。但是,我想将变量A, B, and C
作为字符值存储在名为 my_variables 的向量中。 So:所以:
my_variables <-c("A", "B", "C")
and I have the values 1, 2, 3, stored in a vector called my_values:我将值 1、2、3 存储在名为 my_values 的向量中:
my_values <-1:3
I tried to use this, but it didn't quite work the way I wanted:我尝试使用它,但它并没有像我想要的那样工作:
assign(my_variables, my_values)
This simply assigns "A" "B" "C"
to the variable my_variables, but nothing is assigned to the variable A
.这只是将
"A" "B" "C"
分配给变量 my_variables,但没有分配给变量A
。
I can accomplish what I want to do with an array, but I wonder if there is a more efficient way to do this with vectorized operations?我可以用数组完成我想做的事情,但我想知道是否有更有效的方法来使用矢量化操作来做到这一点? Is there a better way to approach this than using a loop?
有没有比使用循环更好的方法来解决这个问题?
assign
is not vectorized, so you can use Map
here specifying the environment. assign
未矢量化,因此您可以在此处使用Map
指定环境。
Map(function(x, y) assign(x, y, envir = .GlobalEnv), my_variables, my_values)
A
#[1] 1
B
#[1] 2
C
#[1] 3
However, it is not a good practice to have such variables in the global environment.但是,在全局环境中使用此类变量并不是一个好习惯。
Use a named vector :使用命名向量:
name_vec <- setNames(my_values, my_variables)
name_vec
#A B C
#1 2 3
Or named list as.list(name_vec)
.或命名列表
as.list(name_vec)
。
This will do the trick这将解决问题
val = 1:3
var = LETTERS[1:3]
l = as.list(val)
names(l) = var
list2env(l, envir = environment())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.