在每个变量上使用不同的功能逐组折叠数据 [英] Collapse data frame by group using different functions on each variable

查看:81
本文介绍了在每个变量上使用不同的功能逐组折叠数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义

df<-read.table(textConnection('egg 1 20 a
                        egg 2 30 a
                        jap 3 50 b
                        jap 1 60 b'))

st

> df
   V1 V2 V3 V4
1 egg  1 20  a
2 egg  2 30  a
3 jap  3 50  b
4 jap  1 60  b

我的数据没有任何因素,因此我将因素转换为字符:

My data has no factors so I convert factors to characters:

> df$V1 <- as.character(df$V1)
> df$V4 <- as.character(df$V4)  

我想折叠 V1保留的数据帧:

I would like to "collapse" the data frame by V1 keeping:


  • V2的最大值

  • V3的平均值

  • V4的模式(该值在V1组中实际上并没有改变,因此,第一个,最后一个等也可能会发生变化。)

请注意,这是一个一般性问题,例如我的数据集要大得多,并且在折叠时我可能想使用不同的函数(例如,last,first,min,max,variance,st.dev。等代表不同的变量)。因此,函数参数可能会很长。

Please note this is a general question, e.g. my dataset is much larger and I may want to use different functions (e.g. last, first, min, max, variance, st. dev., etc for different variables) when collapsing. Hence the functions argument could be quite long.

在这种情况下,我希望输出以下形式:

In this case I would want output of the form:

> df.collapse
   V1 V2 V3 V4
1 egg  2 25  a
2 jap  3 55  b


推荐答案

plyr软件包将为您提供帮助:

plyr package will help you:

library(plyr)
ddply(df, .(V1), summarize, V2 = max(V2), V3 = mean(V3), V4 = toupper(V4)[1])

由于R不具有模式功能(可能),因此我放置了其他功能。
,但是很容易实现模式功能。

As R does not have mode function (probably), I put other function. But it is easy to implement a mode function.

这篇关于在每个变量上使用不同的功能逐组折叠数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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