Anshul S
Anshul S

Reputation: 281

Rank according to one column and grouby another column

I have to rank a dataframe DF1

DF1

       LC        Day 
1    RM11 2019-02-18    
2    WK15 2019-02-18    
3    AS17 2019-02-19    
4    WK14 2019-02-19
5    RM11 2019-02-19    
6    WK15 2019-02-20
7    AS17 2019-02-22   
8    WK14 2019-02-22   

Here I want to groupby column "LC" & rank by column "Day"

Output should be:

       LC        Day  Rank
1    RM11 2019-02-18   1  
2    WK15 2019-02-18   1
3    AS17 2019-02-19   1
4    WK14 2019-02-19   1
5    RM11 2019-02-19   2 
6    WK15 2019-02-20   2
7    AS17 2019-02-22   2  
8    WK14 2019-02-22   2

I have tried the below code but it is giving me rank in integers:

> workingday = as.data.frame(workingday %>% group_by(LC) %>%
+                               mutate(rank = rank(Day)) %>%
+                               arrange(Day))

Can someone help me with some other code?

Upvotes: 1

Views: 31

Answers (3)

akrun
akrun

Reputation: 887911

Using data.table

library(data.table)
setDT(workingday)[, Rank := frank(as.IDate(Day)), by = LC]

Upvotes: 1

GKi
GKi

Reputation: 39727

You can use ave like:

x$Rank <- ave(unclass(as.Date(x$Day)), x$LC, FUN=order)
x
#    LC        Day Rank
#1 RM11 2019-02-18    1
#2 WK15 2019-02-18    1
#3 AS17 2019-02-19    1
#4 WK14 2019-02-19    1
#5 RM11 2019-02-19    2
#6 WK15 2019-02-20    2
#7 AS17 2019-02-22    2
#8 WK14 2019-02-22    2

Upvotes: 2

klkj
klkj

Reputation: 24

workingday %>%
    group_by(LC) %>%
    mutate(Rank = rank(as.Date(Day)))

Upvotes: 0

Related Questions