Search code examples
rvariable-assignmentassignment-operatorassign

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.

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 (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! 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.

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!


Solution

  • 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 i.e. the 1st 3 values to 2

    assign('a', `[<-`(a, 1:3, 2))
    a
    #[1] 2 2 2 4