a good, practical guidline for “apply” in R.

What You're Doing Is Rather Desperate

At any R Q&A site, you’ll frequently see an exchange like this one:

Q: How can I use a loop to […insert task here…] ?

A: Don’t. Use one of the apply functions.

So, what are these wondrous *apply* functions and how do they work? I think the best way to figure out anything in R is to learn by experimentation, using embarrassingly trivial data and functions.

If you fire up your R console, type “??apply” and scroll down to the functions in the *base* package, you’ll see something like this:

Let’s examine each of those.

**1. apply***Description: “Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.”*

OK – we know about vectors/arrays and functions, but what are these “margins”? Simple: either the rows (1), the columns (2) or both (1:2). By “both”, we mean “apply the…

View original post 1,003 more words