iraciv94
iraciv94

Reputation: 840

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

Upvotes: 0

Views: 580

Answers (1)

iod
iod

Reputation: 7592

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.

Upvotes: 3

Related Questions