Another thing that you might wanna do is average values within a particular factor.

So, this is a very common thing to do.

So, this is now looking at a insect sprays data set.

So, what we have now is different kinds of sprays.

So, in this case, the spray is A, or B, or C, or D, or E or F and then it's

the count of the number of insects that you see with that different spray,

and so one thing that you might want to do is take the sum of the count of

insects that you see for each of the different sprays.

So to do that what you could do is you could take the insect count variable and

pass it to tapply.

And you could say, I would like to tapply,

that means apply along an index, a particular function.

So I'm going to apply to count along the index spray, the function sum.

What that's gonna do is, within each value of spray, it will sum up the counts,

so you get the sum for A and the sum for B and the sum for C.

That's one very brief, shorthand way of calculating those sums.

Another way is what's called split, apply, combine.

So, you can imagine that what you wanna do is, you wanna take the insect

spray counts and you want to split them up by each of the different sprays.

So you can do that with the split function and R and

what you end up now is with a list, where you get the list of the values for

A, the list of the values for B, the list of the values for C and so forth.

So that's the split part of the split apply component.

Then what you can do is you can apply to that list a function.

So here we have the list of different values for

each of the different sprays, and we can use lapply to apply across that list.

So each element of your list, we're going to apply the sum.

So again, we get the same values out, we've summed up the counts for A,

summed up the counts for B, summed up the counts C and so forth.

And now we actually have a list but we may wanna go back to a vector so

that it's easier to manipulate on our.

And so then, we do combining.

We basically unlist the list that we got when we did the apply after the split.