r - 为组 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 在不同组中重新开始?
解决方案
你可以这样做:
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
推荐阅读
- python - 查找任何给定数字的第 n 个数字
- r - 在 R 中看到 left_join 出现意外错误
- java - Is there a a way I can store information with Java without requiring a dedicated server?
- php - woocommerce 基于支付网关的感谢消息
- javascript - Javascript - 如何将数组中对象的第一个元素分配为另一个数组的键
- rest - 更新资源导致位置更改后的 REST 响应
- javascript - How do I return or make null all other EventListeners if another is triggered using vanilla Javascript
- mysql - 在锁定表时重新编号mysql中的主键
- arrays - React:通过字符串映射并为每次迭代发出命令。然后计算结果
- python - 向量的一维卷积