0

I have a dataset which was ordered using function order() in R and same is shown below

A   B   C
1   1   85
1   1   62
1   0   92
2   1   80
2   0   92
2   0   84
3   1   65
3   0   92

I've to print rank based on column A and expected output is shown below

A   B   C   Rank
1   1   85  1
1   1   62  2
1   0   92  3
2   1   80  1
2   0   92  2
2   0   84  3
3   1   65  1
3   0   92  2

Request for expertise in R

Sotos
  • 51,121
  • 6
  • 32
  • 66
Praveen Kumar
  • 107
  • 1
  • 7

1 Answers1

1

A simple base R solution using ave and seq_along is

df$Rank <- ave(df$B, df$A, FUN=seq_along)

which returns

df
  A B  C Rank
1 1 1 85    1
2 1 1 62    2
3 1 0 92    3
4 2 1 80    1
5 2 0 92    2
6 2 0 84    3
7 3 1 65    1
8 3 0 92    2

seq_along returns a vector 1, 2, 3, ... the length of its argument. ave allows the user to apply a function to groups which are determined here by the variable A.

data

df <- read.table(header=TRUE, text="A   B   C
1   1   85
1   1   62
1   0   92
2   1   80
2   0   92
2   0   84
3   1   65
3   0   92")
lmo
  • 37,904
  • 9
  • 56
  • 69