Posts Tagged ‘reflection’

The method in the mirror: reflection in R

17th July, 2011 Leave a comment

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 class, attributes, str and 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 get or 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 getAnywhere.)

#without reflection

#with reflection

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

lapply(ls(), get)

Again, it’s a tiny bit more complicated for S4 classes, which have a variety of extra functions for inspecting them. There’s getMethod, 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.

Tags: ,