Search code examples
reval

Affecting variable through eval or similar


I know that if i have the name of a variable stored like a = "var.name", i can call this var.name by doing eval(as.symbol(a)) or get(a), but i wanted to not only call a variable, but also make changes to it. Example:

names = c("X1","X2")
for(i in names){
    assign(i, cbind(replicate(2,rnorm(3))) #Just creating a 3x2 matrix with dummy data
    ###

At ### i'd like to make a change to the variables, specifically change its column names to "a" and "b".

I tried colnames(get(i)) = c("a","b"), or colnames(eval(as.symbol(i))) = c("a","b"), but they return errors like could not find function "eval<-"


Solution

  • One option could be to create the matrix in the first step, and name and assign to a new name in the second step.

    names = c("X1","X2")
    for(i in names){
      x <- cbind(replicate(2,rnorm(3))) 
      assign(i, provideDimnames(x))
    }   
    
    #--------------
    > X1
                A          B
    A -0.59174062  1.8527780
    B -0.53088643 -3.2713544
    C -0.09330006 -0.5977568
    
    

    Another option would be to assign the dimnames at the time of creation of the matrix.

    for (i in names) {
      x <- matrix(replicate(2, rnorm(3)),
                  ncol = 2,
                  dimnames = list(a = c(LETTERS[1:3]), b = c(LETTERS[1:2])))
      
      assign(i, x)
    }
    
    #-------------------
    > X1
    
       b
    a            A           B
      A -0.2313692 -0.93161762
      B -0.9666849  0.06164904
      C  1.5614446 -0.09391062