The method in the mirror: reflection in R

[This article was first published on 4D Pie Charts » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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
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

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.


Tagged: r, reflection

To leave a comment for the author, please follow the link and comment on their blog: 4D Pie Charts » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)