Need to rank a dataset based on 3 columns in R -


this question has answer here:

i have dataset ordered using function order() in r , same 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 print rank based on column , expected output 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 expertise in r

a simple base r solution using ave , seq_along is

df$rank <- ave(df$b, df$a, fun=seq_along) 

which returns

df   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 vector 1, 2, 3, ... length of argument. ave allows user apply function groups determined here 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") 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -