Skip to content

[R] Dynamic variable name

I was recently asked how to set dynamically the name of a variable in R. I knew how to do this kind of manipulation in PHP (basically, it involves calling the value of another variable as the variable name by a double buck, like $name=’ThisIsTheNameIWant’;$$name=5;), but never saw that in R.

I eventually found the solution at Rosetta Code: the assign function can do this. The syntax is simply:
assign(variableName, variableValue)

If you choose to let the user input the variable name, it may be a good idea to sanitize the name, using the make.names function. Full code:

variableName = readline("Please enter the variable name: ");
variableName = make.names(variableName);
variableValue = readline("Please enter the variable value: ");
assign(variableName, variableValue);

Then, if you want to read the variable, you’ll need to use the get function. Syntax: get(variableName).

Posted in R (R-project).

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA