As a general note, I think it's great that you're puzzling through the code that people show you and asking questions! If you're finding that you need some more background information on R to make sense of things, you might take a look at this thread which is full of really great suggestions for places to learn about R if you're just getting started:
(for instance, if you want to understand more about that weird trick with order()
that I used, I think Hands On Programming with R or The Art of R (both linked in the above thread) are really good resources)