The method in the mirror: reflection in R
Reflection is a programming concept that sounds scarier than it is. There are three related concepts that fall under the umbrella of reflection, and I’ll be surprised if you haven’t come across most of these code ideas already, even if you didn’t know it was called reflection.
The first concept is examination of your variables. In R, this mostly means calling
summary. S4 classes also have the function
showMethods to, ahem, show their methods.
The second concept is accessing variables by name; in R this means calling
getAnywhere, the latter being used for functions that aren’t exported from a package namespace. (Start by using
get; if that doesn’t work, try
#without reflection mean(1:5) #with reflection get("mean")(1:5) getAnywhere("mean")(1:5)
The main use of this is with functions that return names of functions, like
ls. For example, to retrieve every local variable in list form, use
Again, it’s a tiny bit more complicated for S4 classes, which have a variety of extra functions for inspecting them. There’s
getSlots and a bunch of other functions. Try
apropos("^get") to find them.
The third concept is to evaluate code in string form. The mean example from above becomes
eval(parse(text = "mean(1:5)"))
A word of warning about this last concept. It is very powerful, but also one of the easiest ways to write completely incomprehensible buggy code. Don’t use it, except in the last resort.
So there you have it, reflection in three easy steps.