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'
CodePudding user response:
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
CodePudding user response:
Assuming that we have run the code in the Note at the end (copied from the question) this changes the name of q1
. This does change the address of q1
internally but it is transparent to the user who is not affected. It uses only base R and does not use eval
-- the use of which is generally frowned upon.
e <- environment()
names(e[[a]]) <- "new name"
q1
## new name
## 2
or as a one-liner
with(list(e = environment()), names(e[[a]]) <- "new name")
q1
## new name
## 2
Note
q1 = 2
names(q1) = 'this_is_name'
a = 'q1'