You have a vector. Each element belongs to a different group, and the groups are identified by a grouping factor. You want to split the elements into the groups.
Solution
Suppose the vector is x and the factor is f. You can use the split function:
> groups <- split(x, f)
Alternatively, you can use the unstack function:
> groups <- unstack(data.frame(x,f))
Both functions return a list of vectors, where each vector contains the elements for one group.
The unstack function goes one step further: if all vectors have the same length, it converts the list into a data frame.
You have a list, and you want to apply a function to each element of the list.
Solution
Use either the lapply function or the sapply function, depending upon the desired form of the result. lapply always returns the results in list, whereas sapply returns the results in a vector if that is possible:
Your data elements occur in groups. You want to process the data by groups—for example, summing by group or averaging by group.
Solution
Create a grouping factor (of the same length as your vector) that identifies the group of each corresponding datum. Then use the tapply function, which will apply a function to each group of data:
> tapply(x, f, fun)
Here, x is a vector, f is a grouping factor, and fun is a function. The function should expect one argument, which is a vector of elements taken from x according to their group.