The five minutes you spend each week will provide you with a building block you can use in the next two hours at work. Review language basics, discover methods to improve existing R code, explore new and interesting features, and learn about useful development tools and libraries that will make your time programming with R that much more productive.
All series code samples can be downloaded at https://github.com/mnr/five-minutes-of-R.
Skill Level Intermediate
- [Instructor] Apply is a family of functions that substitutes for a for loop. M apply is similar to apply, except it handles multiple arguments and functions. Let's take a look at how this actually works. First let's look at a function, we'll call it repeat. Rep and repeat will take a string or a value or an anything, in this case I'm typing in hello and repeat it a number of times.
So I've typed in hello three and if I hit command return, I get three hellos. Let's say that I wanted to repeat hello once and then repeat hello twice and then repeat hello three times. I could type in the command each time or I could use M apply and I can tell it that the function that I want to apply is rep and then the values that I want to pass to rep are hello and I'd like to do it one time, then two times, then three times, then four times.
So I can give it a range of numbers, one through four. And if I hit return, now what I get is one hello, two hellos, three hellos and four hellos. So what I've done is passed hello to rep, just like I did in line three, but I changed out the repeat value each time it went through. Repeat also has an each value, it looks like this, each, and I can double the values that are applied to repeat.
So if I were to do this, what I would get is six hellos. Because each time you repeat, give it twice as many times. Well, what I can do here is I can go ahead with m apply and add that as a named parameter. Now when I hit m apply, you can see that the first time, it repeats once, but each says to double that. So it goes hello, hello. The second line gives me four hellos, which is a multiplication of two and each, which is two.
So the takeaway here is m apply is a version of apply. It allows you to pass multiple arguments to a function.