英文:
Numbering the group after group by column in R
问题
我想要在同一组中为数字添加标签。我想按date分组,然后在同一组中给出相同的数字。
这是我的数据示例:
df <- data.frame(id = c("RM125","RM126","RM121","RM120","RM128","RM129","RM131","RM133","RM135","RM132"),
                 date = c(rep("1110101",6),rep("1110102",4)))
期望的输出如下:
ID          Date  label
RM125    1110101      1
RM126    1110101      1
RM121    1110101      1
RM120    1110101      1
RM128    1110101      1
RM129    1110101      1
RM131    1110102      2
RM133    1110102      2
RM135    1110102      2
RM132    1110102      2
我尝试了很多代码,如下所示:
df %>% group_by(date) %>% mutate(row_number())
df %>% group_by(date) %>% mutate(group = match(date, unique(date)))
仍然无法工作。任何提示都将不胜感激。
英文:
I want to label number in the same group.I want to group by date then give number in the same group.
Here is my data sample:
df <- data.frame(id = c("RM125","RM126","RM121","RM120","RM128","RM129","RM131","RM133","RM135","RM132"),
                 date = c(rep("1110101",6),rep("1110102",4)))
Deisre Output like:
ID          Date  label
RM125    1110101      1
RM126    1110101      1
RM121    1110101      1
RM120    1110101      1
RM128    1110101      1
RM129    1110101      1
RM131    1110102      2
RM133    1110102      2
RM135    1110102      2
RM132    1110102      2
I have tried many code like
df %>% group_by(date) %>% mutate(row_number())
df %>% group_by(date) %>% mutate(group = match(date, unique(date)))
Still can't work.Any tip is appreciated.
答案1
得分: 0
你尝试过 cur_group_id() 吗?
library(dplyr)
df %>%
mutate(group = cur_group_id(), .by = date)
英文:
Have you tried cur_group_id()?
library(dplyr)
df %>%
mutate(group = cur_group_id(), .by = date)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论