如何使用r对特定范围内的年龄进行分组 [英] how to group ages in specific range using r

查看:1858
本文介绍了如何使用r对特定范围内的年龄进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框

df <- data.frame(age = c(40,42,43,45,47,48,51,50,55),
                 amount = c(456,487,789,231,454,525,421,478,789))

如何将此年龄分组为 seq(40,55,by = 5)并找到这些组的总和?

How can I group this age in to seq(40,55,by=5) and find the aggregate sum of these groups?

我尝试过

aggregate(df$amount, by = list(df$age) , sum)

但是它只给我相同年龄的总和,我需要这个年龄

But it gives me only sum of same age, and I need the age it to be grouped and their aggregate sum.

推荐答案

您可以使用 cut 进行分组年龄,然后汇总金额。

You can use cut to group the ages and then aggregate the amounts.

Age <- cut(df$age, c(seq(40, 55, by = 5), Inf), include.lowest = TRUE)

aggregate(amount ~ Age, df, sum)
#      Age amount
#1 [40,45]   1963
#2 (45,50]   1457
#3 (50,55]   1210

这篇关于如何使用r对特定范围内的年龄进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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