From the course: R for Data Science: Lunch Break Lessons

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

apply and lapply

apply and lapply

- [Instructor] R has a command called apply, and apply is a substitute for a for loop. Let's take a look at how that works. First of all we need a bit of data, so let's go grab a list of all the phones in the world separated out by year and country. We can look at a for loop here. This is one I've created to illustrate what this looks like. This is a for, and each country, and a number of columns of world phones. Let's go ahead and run this real quick. You can see what kind of information we get back from it. It's creating a mean or an average of the world phones by country. Instead of using for loops, in R you have the option of using apply. Let's set up an apply command here. It's A-P-P-L-Y, very simple, parenthesis, and then you tell it what you want to apply something to. We're going to use the data set WorldPhones. Apply allows you to apply the function across rows or across columns, and if I type in a one it's going to apply a function across the row. If I apply two, it's going…

Contents