在R中,对分组后的列进行编号。

huangapple go评论69阅读模式
英文:

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 &lt;- data.frame(id = c(&quot;RM125&quot;,&quot;RM126&quot;,&quot;RM121&quot;,&quot;RM120&quot;,&quot;RM128&quot;,&quot;RM129&quot;,&quot;RM131&quot;,&quot;RM133&quot;,&quot;RM135&quot;,&quot;RM132&quot;),
                 date = c(rep(&quot;1110101&quot;,6),rep(&quot;1110102&quot;,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

text
text
text

df %&gt;% group_by(date) %&gt;% mutate(row_number())
df %&gt;% group_by(date) %&gt;% 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 %&gt;%
mutate(group = cur_group_id(), .by = date)

huangapple
  • 本文由 发表于 2023年6月13日 11:48:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定