Home > R > The method in the mirror: reflection in R

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 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: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: