如何使用带有ddply或聚合返回向量(如Fivenum)的函数? [英] How can I use functions returning vectors (like fivenum) with ddply or aggregate?

查看:91
本文介绍了如何使用带有ddply或聚合返回向量(如Fivenum)的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用几列来拆分数据框,并在每个组上调用fivenum.

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)))

返回值是只有两列的data.frame,第二列是矩阵.如何将其转换为data.frame的普通列?

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?

更新

我希望使用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)
      )

推荐答案

您可以使用do.call递归地在每个矩阵元素上调用data.frame以获得具有矢量元素的data.frame:

You can use do.call to call data.frame on each of the matrix elements recursively to get a data.frame with vector elements:

dim(do.call("data.frame",dfr))
[1] 3 7

str(do.call("data.frame",dfr))
'data.frame':   3 obs. of  7 variables:
 $ Species            : Factor w/ 3 levels "setosa","versicolor",..: 1 2 3
 $ Petal.Width.Min.   : num  0.1 1 1.4
 $ Petal.Width.1st.Qu.: num  0.2 1.2 1.8
 $ Petal.Width.Median : num  0.2 1.3 2
 $ Petal.Width.Mean   : num  0.28 1.36 2
 $ Petal.Width.3rd.Qu.: num  0.3 1.5 2.3
 $ Petal.Width.Max.   : num  0.6 1.8 2.5

这篇关于如何使用带有ddply或聚合返回向量(如Fivenum)的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆