Home > R > Finally, a use for rapply

Finally, a use for rapply

In the apply family of functions, rapply is the unloved ginger stepchild. While lapply, sapply and vapply make regular appearances in my code, and apply and tapply have occasional cameo appearances, in ten years of R coding, I’ve never once found a good use for rapply.

Maybe once a year I take a look at the help page, decide it looks to complicated, and ignore the function again. So today I was very pleased to have found a genuine use for the function. It isn’t life-changing, but it’s quite cute.

Complex classes often have a print method that hides their internals. For example, regression models created by glm are lists with thirty elements, but their print method displays only the call, the coefficients and a few statistics.

# From example(glm)
utils::data(anorexia, package = "MASS")
anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                family = gaussian, data = anorexia)
str(anorex.1)

To see everything, you need to use unclass.

unclass(anorex.1) #many pages of output

unclass has a limitation: it only removes the top level class, so subelements keep their classes. For example, compare:

class(unclass(anorex.1)$qr) # qr
class(unclass(anorex.1$qr)) # list

Using rapply, we can remove classes throughout the whole of the object, turning it into a list of simple objects.

rapply(anorex.1, unclass, how = "replace")

As well as allowing us to thoroughly inspect the contents of the object, it also allows the object to be used with other code that doesn’t understand particular classes.

About these ads
Tags: , , ,
  1. Anonymous
    16th July, 2014 at 3:31 am

    Is there supposed to be an article here?

    • 16th July, 2014 at 7:49 am

      OK, WordPress somehow failed to update the contents. Thanks for letting me know. Now fixed.

  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 204 other followers

%d bloggers like this: