条件分组与新变量

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

Conditional grouping with new Variable

问题

假设我有以下数据集:

|ID |

| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |

我想创建一个新的变量,其中我将具有相同ID编号的所有行相加。它应该如下所示:

ID New
1 4
1 4
1 4
1 4
2 3
2 3
2 3

因为我有四个1和三个2。

英文:

Suppose I have the dataset

|ID |

| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |

I want to create a new variable where I add all the rows with the same ID number. It should look like

ID New
1 4
1 4
1 4
1 4
2 3
2 3
2 3

Because I have four 1s, and three 2s.

答案1

得分: 1

  1. df %>% summarise(n = n(), .by = ID)
  2. ID n
  3. 1 1 4
  4. 2 2 3
  5. # 或者,如果你想要重复项:
  6. df %>% mutate(n = n(), .by = ID)
  7. ID n
  8. 1 1 4
  9. 2 1 4
  10. 3 1 4
  11. 4 1 4
  12. 5 2 3
  13. 6 2 3
  14. 7 2 3
英文:
  1. df %>% summarise(n = n(), .by = ID)
  2. ID n
  3. 1 1 4
  4. 2 2 3
  5. # or, if you want duplicates:
  6. df %>% mutate(n = n(), .by = ID)
  7. ID n
  8. 1 1 4
  9. 2 1 4
  10. 3 1 4
  11. 4 1 4
  12. 5 2 3
  13. 6 2 3
  14. 7 2 3

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

发表评论

匿名网友

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

确定