简体   繁体   中英

Call a variable name within another variable in R

I have a variable:

Person1 = "friend"

That I save in a second variable, namely:

Real_friend = Person1

Is it possible to have a function like this:

   output <- myfunc(Real_friend)
   myfunc <- function(v1) {
     # do something with v1
     # so that it prints "Person1" when 
     # this function is called 
     #
     # instead of "friend"
     return ()
   }

output = "Person1"

I have tried to apply the method: deparse(substitute(v1)) suggested here:

How to convert variable (object) name into String

but it does not seem to work. Thanks so much in advance

When you write Real_friend = Person1 , R just puts the contents of Person1 into Real_friend, it doesn't save any record that this was done by way of Person1. One thing you could do, is to pass "Person1" to Real_friend, and then either call on Real_friend when you need "Person1 " as the output, or call on get(Real_Friend) when you want the contents of Person1.

Person1<-"John"
> Real_friend<-"Person1"
> Real_friend
[1] "Person1"
> get(Real_friend)
[1] "John"

A second way of achieving something similar, using the link you provided, is to do:

> Real_friend<-substitute(Person1)

Now the contents of Real_friend are the unevaluated call for Person1 :

> Real_friend
Person1

You can get the name of the variable as a string using deparse , or you can get the content of the variable using eval :

> deparse(Real_friend)
[1] "Person1"
> eval(Real_friend)
[1] "John"

Again, none of these options allows you to start with Real_friend<-Person1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM