Dplyr add group id sequence?

I have a dataset as shown below, it was created by dplyr and is currently grouped by "Stage", how can I create a sequence based on the unique incremental value of Stage, starting from 1 (for example, for line $ 4 there should be 1 line # 1 and # 8 should be 4)

     X   Y Stage Count
1   61  74     1     2
2   58  56     2     1
3   78  76     0     1
4  100 100    -2     1
5   89  88    -1     1
6   47  44     3     1
7   36  32     4     1
8   75  58     1     2
9   24  21     5     1
10  12  11     6     1
11   0   0    10     1

I tried the approach in the bottom column but didn't work. how to mutate a column with an id in a group

Thank.

+4
source share
2 answers

Here is another dplyr solution:

> df
# A tibble: 11 Γ— 4
       X     Y Stage Count
   <dbl> <dbl> <dbl> <dbl>
1     61    74     1     2
2     58    56     2     1
3     78    76     0     1
4    100   100    -2     1
5     89    88    -1     1
6     47    44     3     1
7     36    32     4     1
8     75    58     1     2
9     24    21     5     1
10    12    11     6     1
11     0     0    10     1

To create a group id, use dpylr group_indicies:

i <- df %>% group_indices(Stage)
df %>% mutate(group = i)

# A tibble: 11 Γ— 5
       X     Y Stage Count group
   <dbl> <dbl> <dbl> <dbl> <int>
1     61    74     1     2     4
2     58    56     2     1     5
3     78    76     0     1     3
4    100   100    -2     1     1
5     89    88    -1     1     2
6     47    44     3     1     6
7     36    32     4     1     7
8     75    58     1     2     4
9     24    21     5     1     8
10    12    11     6     1     9
11     0     0    10     1    10

, . .

+2

%>% ungroup() %>% mutate(test = rank(Stage)), .

     X   Y Stage Count test
1  100 100    -2     1  1.0
2   89  88    -1     1  2.0
3   78  76     0     1  3.0
4   61  74     1     2  4.5
5   75  58     1     2  4.5
6   58  56     2     1  6.0
7   47  44     3     1  7.0
8   36  32     4     1  8.0
9   24  21     5     1  9.0
10  12  11     6     1 10.0
11   0   0    10     1 11.0

, , ....

, , Node

lvs <- levels(as.factor(Node$Stage))
Node %>% mutate(Rank = match(Stage,lvs))
+1

All Articles