识别一组计数中的索引号

Identifying the index number in a group of counts

我有一个 df 需要按组进行计数和分组。 但我也想确定分组中观察的索引(?)。

A4 个观察,我想为第 3 个 A 观察附上 3 的索引。

df %>% 
group_by(group) %>% 
mutate(count = n())

#   group index count
#1      A    1     4
#2      A    2     4
#3      A    3     4
#4      A    4     4
#5      B    1     1
#6      B    2     1
#7      C    1     3
#8      C    2     3
#9      C    3     3
#10     D    1     1

您想使用 window function row_number():

df %>%
  group_by(group) %>%
  mutate(index = row_number()) # explicit would be row_number(group)