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

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

Numbering the group after group by column in R

问题

我想要在同一组中为数字添加标签。我想按date分组,然后在同一组中给出相同的数字。

这是我的数据示例:

  1. df <- data.frame(id = c("RM125","RM126","RM121","RM120","RM128","RM129","RM131","RM133","RM135","RM132"),
  2. date = c(rep("1110101",6),rep("1110102",4)))

期望的输出如下:

  1. ID Date label
  2. RM125 1110101 1
  3. RM126 1110101 1
  4. RM121 1110101 1
  5. RM120 1110101 1
  6. RM128 1110101 1
  7. RM129 1110101 1
  8. RM131 1110102 2
  9. RM133 1110102 2
  10. RM135 1110102 2
  11. RM132 1110102 2

我尝试了很多代码,如下所示:

  1. df %>% group_by(date) %>% mutate(row_number())
  2. 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:

  1. 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;),
  2. date = c(rep(&quot;1110101&quot;,6),rep(&quot;1110102&quot;,4)))

Deisre Output like:

  1. ID Date label
  2. RM125 1110101 1
  3. RM126 1110101 1
  4. RM121 1110101 1
  5. RM120 1110101 1
  6. RM128 1110101 1
  7. RM129 1110101 1
  8. RM131 1110102 2
  9. RM133 1110102 2
  10. RM135 1110102 2
  11. RM132 1110102 2

I have tried many code like

text
text
text

  1. df %&gt;% group_by(date) %&gt;% mutate(row_number())
  2. 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() 吗?

  1. library(dplyr)
  2. df %>%
  3. mutate(group = cur_group_id(), .by = date)
英文:

Have you tried cur_group_id()?

  1. library(dplyr)
  2. df %&gt;%
  3. 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:

确定