Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a column to enumerate a set of events

Tags:

r

dplyr

plyr

I have data on a set of events that happen in some order. I would like a column that enumerates that set of events: this row is the first time, this row is the second time etc. The data will look like the following:

S   Time
A     3
A     4
A     5
A     10
B     4
B     9
B     1
B     37

Where S is some kind of session ID and time is obviously time. I would want the following result column added:

S   Time   Order
A     3      1
A     5      3
A     4      2
A     10     4
B     4      2
B     9      3
B     1      1
B     37     4

For each of the session IDs, I want to have a column that gives an ordering on the rows based on time. I'm using dplyr and I'm hoping for a concise dplyr way of doing this.

like image 319
divide_by_zero Avatar asked Apr 28 '15 18:04

divide_by_zero


2 Answers

Try

 library(dplyr)
 df1 %>%
      group_by(S) %>% 
      mutate(Order=rank(Time))
like image 81
akrun Avatar answered Oct 06 '22 23:10

akrun


You could also do:

df %>% group_by(S) %>% mutate(Order = row_number(Time))

In the dplyr package, row_number() is equivalent to rank(ties.method = "first")

like image 21
Steven Beaupré Avatar answered Oct 06 '22 22:10

Steven Beaupré