azad azad - 17 days ago 7
R Question

datewise grouping data in R

I have sample dataframe:-

date item1 item2 item3
17-11-2016 2A hp cnf
12-11-2016 1A bp wl
13-11-2016 3A sp dl
14-11-2016 1A hp cnf
16-11-2016 2A bp cnf
10-11-2016 1A sp wl
17-11-2016 2A hp wl


i want to group data based on all coloumns date,item1 and item2, so that particular coloumn with same value will come to same group.

expected output--

date item1 item2 item3 grp
17-11-2016 2A hp cnf 1
17-11-2016 2A hp wl 1
12-11-2016 1A bp wl 2
13-11-2016 3A sp dl 3
14-11-2016 1A hp cnf 4
16-11-2016 2A bp cnf 5
10-11-2016 1A sp wl 6

Answer

You can do it this way:

DF <- data.frame(date = c("17-11-2016","12-11-2016","13-11-2016","14-11-2016",
                          "16-11-2016","10-11-2016","17-11-2016"),
                 item1 = c("2A","1A","3A","1A","2A","1A","2A"),
                 item2 = c("hp","bp","sp","hp","bp","sp","hp"),
                 item3 = c("cnf","wl","dl","cnf","cnf","wl","wl")
                 )
DF$grp <- as.numeric(factor(paste(DF$date,DF$item1,DF$item2)))
DF[order(DF$grp),]
        date item1 item2 item3 grp
6 10-11-2016    1A    sp    wl   1
2 12-11-2016    1A    bp    wl   2
3 13-11-2016    3A    sp    dl   3
4 14-11-2016    1A    hp   cnf   4
5 16-11-2016    2A    bp   cnf   5
7 17-11-2016    2A    hp    wl   6
1 17-11-2016    2A    hp   cnf   6
Comments