Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Just a quick note on a short hack that I cobbled together this morning. I have an analysis where I need to perform the same set of operations to a list of variables. In order to do this in a compact and robust way, I wanted to write a loop that would run through the variables and apply the operations to each of them in turn. This can be done using get() and assign().

To illustrate the procedure, I will use the simple example of squaring the numerical values stored in three variables. First we initialise the variables.

> x = 1
> y = 2
> z = 3


Then we loop over the variable names (as strings), creating a temporary copy of each one and applying the operation to the copy. Then the copy is assigned back to the original variable.

> for (n in c("x", "y", "z")) {
+   v = get(n)
+   #
+   v = v**2
+   #
+   assign(n, v)
+ }


Finally we check that the operation has been executed as expected.

> x
 1
> y
 4
> z
 9


This is perhaps a little wasteful in terms of resources (creating the temporary variables), but does the job. Obviously in practice you would only implement this sort of solution if there were either a large number of variables to be transformed or the transformation required a relatively complicated set of operations.