r - Perform grouping by order and value -
I need to assign a group of events going to one line. I explain by example:
Incidents & lt; - c ('b', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'b', 'b', 'b' And I want to produce this result (group letter), 'E', 'E', 'E', 'E', 'D', 'D', 'D' / code> Going to one line):
group <-c (1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4 , 4, 4, 4, 5, 5, 5)
The obvious solution for me is:
1 + cumsum (cbind (c = events , N = c (NA_character_, rev (rev (events) [- 1]))), 1, function (x)! Na (x ["n"]) & amp; amp; amp; x ["c"]! = X ["n"]))
Is there a more beautiful way to do this?
Use factors if you do not really care about ordering levels, just do the following:
Factors (events)
It should be sufficient for most situations, although I do not know what you are planning to do next.
If you take care of the order,
factor (event, level = unique (event))
Levels want to leave and only want integer representation:
as.integer (factor (events, level = unique (events)) # [1] 1 2 2 2 2 2 2 2 2 2 3 4 4 5 6 7 8 9 10 11 12 13 14 15 16 16 17 18 # [28] 18 1921 21 22
Another small solution:
match (events, unique (events))
edit : the level of assuming may appear at one In the embodied subset and if you want to separate them with a new value (cf with your editing) then you can:
cumsum (c (TRUE, head, events, -1) ! = Tails (events, -1))
or
inverse.rle (inside.list (rle (event), value & lt; - Seq_along (value))
Comments
Post a Comment