I use the following code to summarize my data, grouped by Compound, Replicate and Mass.
summaryDataFrame <- ddply(reviewDataFrame, .(Compound, Replicate, Mass),
.fun = calculate_T60_Over_T0_Ratio)
An unfortunate side effect is that the resulting data frame is sorted by those fields. I would like to do this and keep Compound, Replicate and Mass in the same order as in the original data frame. Any ideas? I tried adding a “Sorting” column of sequential integers to the original data, but of course I can’t include that in the .variables since I don’t want to ‘group by’ that, and so it is not returned in the summaryDataFrame.
Thanks for the help.
This came up on the
plyrmailing list a while back (raised by @kohske no less) and this is a solution offered by Peter Meilstrup for limited cases:Please do read the thread for Hadley’s notes about why this functionality may not be general enough to roll into
ddply, particularly as it probably applies in your case as you are likely returning fewer rows with each piece.Edited to include a strategy for more general cases
If
ddplyis outputting something that is sorted in an order you do not like you basically have two options: specify the desired ordering on the splitting variables beforehand using ordered factors, or manually sort the output after the fact.For instance, consider the following data:
using strings, for now.
ddplywill sort the output, which in this case will entail the default lexical ordering:If the resulting data frame isn’t ending up in the “right” order, it’s probably because you really want some of those variables to be ordered factors. Suppose that we really wanted
x1andx2ordered like so:Now when we use
ddply, the resulting sort will be as we intend:The moral of the story here is that if
ddplyis outputting something in an order you didn’t intend, it’s a good sign that you should be using ordered factors for the variables you’re splitting on.