I would like to split my data frame using a couple of columns and call let's say fivenum
on each group.
aggregate(Petal.Width ~ Species, iris, function(x) summary(fivenum(x)))
The returned value is a data.frame with only 2 columns and the second being a matrix. How can I turn it into normal columns of a data.frame?
Update
I want something like the following with less code using fivenum
ddply(iris, .(Species), summarise,
Min = min(Petal.Width),
Q1 = quantile(Petal.Width, .25),
Med = median(Petal.Width),
Q3 = quantile(Petal.Width, .75),
Max = max(Petal.Width)
)
As far as I know, there isn't an exact way to do what you're asking, because the function you're using (fivenum) doesn't return data in a way that can be easily bound to columns from within the 'ddply' function. This is easy to clean up, though, in a programmatic way.
Step 1: Perform the
fivenum
function on each 'Species' value using the 'ddply' function.Now, the 'fivenum' function returns a list, so we end up with 5 line entries for each species. That's the part where the 'fivenum' function is fighting us.
Step 2: Add a label column. We know what Tukey's five numbers are, so we just call them out in the order that the 'fivenum' function returns them. The list will repeat until it hits the end of the data.
Step 3: With the labels in place, we can quickly cast this data into a new shape using the 'dcast' function from the 'reshape2' package.
All that junk at the end are just specifying the column order, since the 'dcast' function automatically puts things in alphabetical order.
Hope this helps.
Update: I decided to return, because I realized there is one other option available to you. You can always bind a matrix as part of a data frame definition, so you could resolve your 'aggregate' function like so:
This is my solution:
You can use
do.call
to calldata.frame
on each of the matrix elements recursively to get a data.frame with vector elements:Here is a solution using
data.table
(while not specifically requested, it is an obvious compliment or replacement foraggregate
orddply
. As well as being slightly long to code, repeatedly callingquantile
will be inefficient, as for each call you will be sorting the dataOr, using a single call to
quantile
using the appropriateprob
argument.Note that the names of the created columns are not syntactically valid, although you could go through a similar renaming using
setnames
EDIT
Interestingly,
quantile
will set the names of the resulting vector if you setnames = TRUE
, and this will copy (slow down the number crunching and consume memory - it even warns you in the help, fancy that!)Thus, you should probably use
Or, if you wanted to return the named list, without
R
copying internally