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.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA