使用cut()和group_by()

时间:2018-04-13 10:05:40

标签: r dplyr

我试图将连续变量分成间隔,根据观察组改变切割值。有一个similar question asked previously,但它只涉及一个列,而我想要找到一个可以推广到group_by() dplyr函数的解决方案,它允许要为分组选择多个列。

这是一个基本的示例数据集:

df <- data.frame(group = c(rep("Group 1", 10),
                           rep("Group 2", 10)),
                 subgroup = c(1,2),
                 value = 1:20)

创建:

     group subgroup value
1  Group 1        1     1
2  Group 1        2     2
3  Group 1        1     3
4  Group 1        2     4
5  Group 1        1     5
6  Group 1        2     6
7  Group 1        1     7
8  Group 1        2     8
9  Group 1        1     9
10 Group 1        2    10
11 Group 2        1    11
12 Group 2        2    12
13 Group 2        1    13
14 Group 2        2    14
15 Group 2        1    15
16 Group 2        2    16
17 Group 2        1    17
18 Group 2        2    18
19 Group 2        1    19
20 Group 2        2    20

出于此问题的目的,我们假设我们要将组拆分为12的值,具体取决于该值是高于还是低于该组的平均值。分组应由groupsubgroup完成,预期输出为:

     group subgroup value cut
1  Group 1        1     1   1
2  Group 1        2     2   1
3  Group 1        1     3   1
4  Group 1        2     4   1
5  Group 1        1     5   1
6  Group 1        2     6   2
7  Group 1        1     7   2
8  Group 1        2     8   2
9  Group 1        1     9   2
10 Group 1        2    10   2
11 Group 2        1    11   1
12 Group 2        2    12   1
13 Group 2        1    13   1
14 Group 2        2    14   1
15 Group 2        1    15   1
16 Group 2        2    16   2
17 Group 2        1    17   2
18 Group 2        2    18   2
19 Group 2        1    19   2
20 Group 2        2    20   2

我希望得到一个输出:

df %>%
  group_by(group, subgroup) %>%
  # INSERT MAGIC FUNCTION TO BIN DATA

2 个答案:

答案 0 :(得分:4)

对于这种情况,您不一定需要cut。使用:

df %>%
  group_by(group, subgroup) %>%
  mutate(cut_grp = (value > mean(value)) + 1)

给出:

# A tibble: 20 x 4
# Groups:   group, subgroup [4]
   group   subgroup value cut_grp
   <fct>      <dbl> <int>   <dbl>
 1 Group 1       1.     1      1.
 2 Group 1       2.     2      1.
 3 Group 1       1.     3      1.
 4 Group 1       2.     4      1.
 5 Group 1       1.     5      1.
 6 Group 1       2.     6      1.
 7 Group 1       1.     7      2.
 8 Group 1       2.     8      2.
 9 Group 1       1.     9      2.
10 Group 1       2.    10      2.
11 Group 2       1.    11      1.
12 Group 2       2.    12      1.
13 Group 2       1.    13      1.
14 Group 2       2.    14      1.
15 Group 2       1.    15      1.
16 Group 2       2.    16      1.
17 Group 2       1.    17      2.
18 Group 2       2.    18      2.
19 Group 2       1.    19      2.
20 Group 2       2.    20      2.

答案 1 :(得分:4)

如果您想使用cut,可以这样做:

df %>% 
  group_by(group, subgroup) %>% 
  mutate(bin = cut(value, breaks = c(-Inf, mean(value), Inf), labels = c(1,2)))