[英]How to assign a name to a specific element of a vector in R
My question is: How to assign a name to a specific element of a vector in R, particularly, using the assign(x, value)
function. 我的问题是:如何为R中的向量的特定元素分配名称,尤其是使用
assign(x, value)
函数。
Normally, to assign a value to a specific element of a vector, I would do as follows: 通常,要将值分配给向量的特定元素,我将执行以下操作:
agent1[2] <- TRUE
But, this is not possible for me , because my (pre-assigned) variables are being called in a for-loop as follows: 但是, 这对我来说是不可能的 ,因为我的(预分配的)变量在如下的for循环中被调用:
for (i in 1:10) {
assign(paste("agent", i, "[2]", sep=""), TRUE)
}
Unfortunately, it seems that the assign function doesn't work for assigning values to specific elements in a vector ! 不幸的是,似乎assign函数不能为向量中的特定元素分配值 ! So while the following
所以虽然以下
for (i in 1:10) {
assign(paste("agent", i, "[2]", sep=""), TRUE)
}
does work to assign the TRUE value to agent1 to agent10, I cannot pick out that it assign the value to only the first (or nth) element in each of the agent vectors. 确实可以将agent1的TRUE值分配给agent10,我无法挑出它仅将值分配给每个agent向量中的第一个(或第n个)元素 。
In a simple case, this can be seen in the following: 在一个简单的情况下,可以在以下内容中看到:
a <- 1:4
a[1] <- 2
a[1] == 2 # TRUE
However, 然而,
a <- 1:4
assign("a[1]", 2)
a[1] == 2 # FALSE
I'd appreciate any help on how to get around this. 我将非常感谢您提供有关如何解决此问题的帮助。 Thanks!
谢谢!
We can try 我们可以试试
assign('a', `[<-`(a, 1, 2))
a[1]==2
#[1] TRUE
If we need to change the values for a range of index ie the 1st 3 values to 2 如果我们需要将索引范围的值(即第一个3值)更改为2
assign('a', `[<-`(a, 1:3, 2))
a
#[1] 2 2 2 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.