Q:

Sorting and numbering can be easier (in R)

First: I want to sort a dataframe and then add a rank to the dataframe.
df <- data.frame(a = 3:1, b = 6:4, Rank = NA) # create dataframe
df <- df[order(df[, 1], df[, 2]), ] # sort dataframe
for ( i in 1:nrow(dataframe) ) dataframe[i, 3] <- i # add the ranking

Second: I want to sort within a group g
df <- data.frame(g = sample(1:4, 4), num = 1:20, Rank = NA) 

df <- df[order(df[, 1], df[, 2]), ]

row <- 1 

for (x in 1:4) {
        rank <- 1
        df[row, 3] <- rank # adding the number one to list
        row <- row + 1 # move to the next row! 
        while (df[row - 1, 1] == df[row, 1] & row < length(df[,1]) + 1){ 
               # Check if state is the last row still same same, otherwise stop next loop!   
                rank <- rank + 1 # adding next to rank!
                df[row, 3] <- rank # Put rank in dataframe!
                row <- row + 1 # move to next row
        }
}  

it works but I would like to accomplish the same tasks with more parsimonious or efficient coding.

A:

Try:
set.seed(123)
df = data.frame(g=sample(1:4, 4), num = 1:20, Rank = NA) 
library(dplyr)
df %>% group_by(g) %>% arrange(num) %>% mutate(rank = seq_along(g))
Source: local data frame [20 x 4]
Groups: g

   g num Rank rank
1  1   3   NA    1
2  1   7   NA    2
3  1  11   NA    3
4  1  15   NA    4
5  1  19   NA    5
6  2   1   NA    1
7  2   5   NA    2
8  2   9   NA    3
9  2  13   NA    4
10 2  17   NA    5
11 3   2   NA    1
12 3   6   NA    2
13 3  10   NA    3
14 3  14   NA    4
15 3  18   NA    5
16 4   4   NA    1
17 4   8   NA    2
18 4  12   NA    3
19 4  16   NA    4
20 4  20   NA    5

