7.2 Repeat an operation on a list - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
<v Voiceover>Lists are</v> a great way to store various R objects all in one object. Iterating over a list is done simply using the l apply function. So to do this, let's make ourselves a list. The list gets list, the first element we will call a, and we'll make it a matrix of one through nine, with three rows. Then we'll say b is simply the vector one through five, and c, we will make another matrix, we'll say that's one through four with two rows. Notice what I just did here? I didn't specify n row equals two, I just typed in two, because the arguments are picked up positionally, and lastly, I'll do one more element that is d equals two. We can look at this list, and see we have a matrix, a vector, a matrix and a single number, which remember, even a single number is still a vector of length one. So let's say we want to sum up each element of this list. And when you sum up a matrix, it just sums up all the numbers, it doesn't matter that it's two dimensional. We could build it for loop end, loop through this end, call sum in each one, or we could just call l apply, have that call sum on each element of the list. So to do that, we type in l apply, tell it what we want to apply over, which is the list, and then the function we want to apply, which is sum. We run this, and we get 45, 15, 10 and two. Works perfectly, and when you use l apply, the result of l apply that comes back is stored as a list, and if there are names on the original list, those names are maintained. Often times, instead of getting a list back, you just want a simple vector, particularly when just looking at a simple number like the sum of something. That's where this handy little shortcut function, s apply, comes in. Now s apply does its best to return a vector, instead of returning a list. If it can't return a vector, it will return a list, but let's see if it can do it in this situation. We'll do s apply the list, and sum, just like with l apply, and now it got us back a beautiful named vector, nice, easy, compact to use. You will find yourselves at varying times using l apply or s apply, depending on what you want back. These are both very fast, quick functions, that really makes life easier. And l apply is versatile, well, it seems like it takes in just a list, it can take in a vector, because, remember, underneath it all, vectors and lists are the same. So let's create a vector, say, the names, and I'll put in there, Jared, Deb and Paul. And right here, we could do l apply on the names, and we'll say, n char. Now again, this is kind of a silly example, because we could of just done n char directly, but I just want to see how it works. And we get, five in Jared, three in Deb, four in Paul. L apply and s apply are great, handy functions that can really quickly iterate over lists.