Search code examples
rstringvariablesnames

How to get the name of a variable as a string in a loop?


I want to create a function to display some R variables' names properly.

I tried using deparse(substitute(variable)) which works fine but I haven't been able to make it work inside a loop

a = 5
b = 6
c = 7
myobjects = c(a, b, c)

for (i in 1:3){
  cat(deparse(substitute(myobjects [i])), " : ", myobjects [i], "\n")
}

which returns

myobjects[i]  :  5 
myobjects[i]  :  6 
myobjects[i]  :  7

instead of

a : 5
b : 6
c : 7

Solution

  • The 'myobjects' contain only the values of the objects 'a', 'b', 'c'. If we need to get the original objects, create a named vector and get the names

    myobjects <- c(a = a, b = b, c = c)
    for(i in 1:3) cat(names(myobjects[i]), " : ", myobjects[i], "\n")
    #a  :  5 
    #b  :  6 
    #c  :  7 
    

    Or as @IceCreamToucan mentioned in the comments, it can be vectorized (without a for looop) as paste does vectorization

    cat(paste0(names(myobjects), ' : ', myobjects), '\n', sep = '\n')