Goal: To create a new variable whose name uses the value of a previously assigned variable in R.
Motivation: Naming many variables according to some value related to the associated command's property (e.g., an alpha
value of 0.75
specified for the bar fill on one chart and the point colour on another chart) would make it possible to store many objects with small changes between them on-the-fly without having to change each variable's name every time the value is changed.
Continuing with the example of the alpha
value given to different plots (above), this should allow us to change the variable value from 0.75
to 0.25
, re-run the plotting commands, and store these plots in variables representatively named for the new opacity being tested.
Simple Example:
First, a value of 42
is used:
number <- 42
var1_number <- rnorm(number)
var2_number <- runif(number)
var3_number <- log(number)
var4_number <- exp(number)
Then, the value is changed to 17
:
number <- 17
var1_number <- rnorm(number)
var2_number <- runif(number)
var3_number <- log(number)
var4_number <- exp(number)
Desired output:
The eight variables should be stored in the R environment as:
Values | |
---|---|
var1_42 |
num [1:42] -0.2298 -0.6823 0.0871 -0.7689 0.1142 . . . |
var1_17 |
num [1:17] 1.241 1.781 1.668 -0.446 -1.668 . . . |
var2_42 |
num [1:42] 0.6926 0.5927 0.7441 0.9804 0.0202 . . . |
var2_17 |
num [1:17] 0.1307 0.3907 0.0599 0.082 0.6091 . . . |
var3_42 |
3.73766961828337 |
var3_17 |
2.83321334405622 |
var4_42 |
1739274941520500992 |
var4_17 |
24154952.7535753 |
Attempts:
Using the exact example provided above results in the creation of four variables named explicitly as written: var1_number
, var2_number
, var3_number
, var4_number
.
Since the variable names are not retrieving an actual value from the defined number
variable, the names remain the same and the variables are overwritten when the value stored in number
is changed.
Also, using backticks to indicate a variable does NOT work (i.e., var1_`number` <- rnorm(number)
) as R interprets them as "unexpected symbol"s.