如何创建一个列,包括R中另一列的最大值? [英] how to create a column including the maximum value of another column in R?

查看:122
本文介绍了如何创建一个列,包括R中另一列的最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用R,我想创建一个新列(MaxAct),显示不同列(ActNo)的最大数,同时按两个因子(HHID和PERID)分组

Using R, I would like to create a new column (MaxAct) showing the maximum numbers of a different column (ActNo) while grouping by two factors (HHID and PERID)

例如,我有这个数据集:

For example, I have this data set:

UID HHID PERID ActNo
1   1000 1     1
2   1000 1     2
3   1000 1     3
4   1000 2     1
5   1000 2     2
6   2000 1     1
7   2000 1     2
8   2000 1     3
9   2000 1     4
10  2000 2     1
11  2000 2     2

然后我要添加新列(MaxAct)如下:

Then I want to add the new column (MaxAct) as follows:

UID HHID PERID ActNo MaxAct
1   1000 1     1     3
2   1000 1     2     3
3   1000 1     3     3
4   1000 2     1     2
5   1000 2     2     2
6   2000 1     1     4
7   2000 1     2     4
8   2000 1     3     4
9   2000 1     4     4
10  2000 2     1     2
11  2000 2     2     2


推荐答案

dat$MaxAct <- with(dat, ave(ActNo, HHID, PERID, FUN=max) )

涉及单个向量和分组的问题,其中您希望结果的长度等于行计数, ave 是您的选择的功能。对于更复杂的问题,可能需要 lapply(split(dat,fac),FUN)方法或使用 do.call(rbind,by ...))

For problems involving single vectors and grouping where you want the length of the result to equal the row count, ave is your function of choice. For more complicated problems, the lapply(split(dat, fac), FUN) approach may be needed or use do.call(rbind, by( ...))

如果您缺少值:

dat$MaxAct <- with(dat, ave(ActNo, HHID, PERID, FUN=function(x) max(x, na.rm=TRUE) )  )

这篇关于如何创建一个列,包括R中另一列的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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