Search code examples
rvariablesdynamic-variables

Picking values dynamically from variables in R


I have 10 variables declared as numeric vectors in R. They are like

 A1 = {10,12,13,14.....}
 A2 = {15,18,19,20.....}
 A3 = {99,88,76,90,....}

and they continue till A10.

Now I want to pick the values of these variables using a for loop and assign them to a variable names created dynamically. I can use assign to create dynamic variables but I am not able to pick these values.

So I want to pick values like

x = A&i # Or Something that picks the value of vector using for loop

I have tried paste() but to no success.

assign(paste("highrange",i,sep=""),(paste("A",i,sep="")-3*paste(A,i,sep="")))

Solution

  • We can use get():

    #data
    A1 = c(10,12,13,14)
    A2 = c(15,18,19,20)
    
    #index
    An <- 1
    Aix <- 2
    
    #assign
    assign("myVar", get(paste0("A", An))[Aix])
    
    #result
    myVar
    # [1] 12