分组2变量(年龄和性别)并找到金额

时间:2019-07-22 18:11:51

标签: r data-manipulation

在数据框下方给出

Age Gender  Amount
55  M   100
30  F   200
35  M   300
50  M   560
58  F   321
60  F   121

团体年龄(seq(30,60,by = 5)

输出应为

(30,35) F   200
(50,55) M   560
(55,60) M   100
(55,60) F   442

1 个答案:

答案 0 :(得分:0)

library(tidyverse)
df = tibble(Age = c(55, 30, 35, 50, 58, 60), Gender = c("M", "F", "M", "M","F","F"), Amount = c(100, 200, 300, 560, 321, 121))

df %>% mutate(Age.new = cut(Age, seq(30, 60, 5), include.lowest = TRUE)) %>% group_by(Age.new, Gender) %>% summarise(sum(Amount))