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.
Try
library(dplyr)
df1 %>%
group_by(S) %>%
mutate(Order=rank(Time))
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With