首页 > 解决方案 > 为组 dplyr 中的唯一值分配唯一编号?

问题描述

我想在按“prop”分组后根据“well”的值生成列 well_rep。

出色地 支柱 well_rep
C03 0 1
C03 0 1
C03 0 1
C03 0 1
C03 0 1
C05 0 2
C05 0 2
C05 0 2
C05 0 2
C05 0 2
C05 0 2
C05 0 2
D02 50 1
D02 50 1
D02 50 1
D02 50 1
D02 50 1
D02 50 1
D02 50 1
D02 50 1
D02 50 1
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
E07 50 2
F02 50 3
F02 50 3
F02 50 3
F02 50 3
F02 50 3
F02 50 3
F02 50 3
F02 50 3

类似 cur_group_id 但数字从 1 在不同组中重新开始?

标签: rdplyr

解决方案


你可以这样做:

df %>%
  group_by(prop) %>%
  mutate(well_rep = as.numeric(as.factor(well)))
# A tibble: 40 x 3
# Groups:   prop [2]
   well   prop well_rep
   <chr> <int>    <dbl>
 1 C03       0        1
 2 C03       0        1
 3 C03       0        1
 4 C03       0        1
 5 C03       0        1
 6 C05       0        2
 7 C05       0        2
 8 C05       0        2
 9 C05       0        2
10 C05       0        2

推荐阅读