rtidyevalnon-standard-evaluation

How can I rename an object using Non standard evaluation in R


Context

I have a named vector q1 = 2. The object name is stored in a = 'q1'.

I can change q1's name by names(q1) = 'this_is_name'.

Then I trid to use non standard evaluation to change q1's name.

I thought names(q1) = 'new_name' and names(sym(a)) = 'new_name' will do the same, but it is not.

Question

How can I rename the object that get access by a in R?

In other word, How can I make names(sym(a)) = 'new_name' do the same as names(q1) = 'new_name'.

Reproducible code

q1 = 2
names(q1) = 'this_is_name'
a = 'q1'


names(q1) = 'new_name' 

names(sym(a)) = 'new_name' # I expect the code should do the same as names(q1) = 'new_name' 


Solution

  • To actually change the object q1 you can use get and assign, both in base R

    assign(a, setNames(get(a), 'new_name'))
    
    q1
    #> new_name 
    #>        2
    

    Created on 2022-10-09 with reprex v2.0.2