r - indexing sub groups in a dataframe -


this question has answer here:

i looking smart way index subcategories within dataframe.
i've created simple reproducible example below. how code following step go input output (ie how can code creation of color_id variable)?

thank in advance view on this!

input <- data.frame(label = c("red", "red", "blue", "green", "green", "green", "orange"), count = c(2, 2, 1, 3, 3 ,3, 1)) 

enter image description here

output <- data.frame(label = c("red", "red", "blue", "green", "green", "green", "orange"), count = c(2, 2, 1, 3, 3 ,3, 1), color_id = c(1, 2, 1, 1, 2, 3, 1)) 

enter image description here

best regards

using data.table:

library(data.table) setdt(input)[ , color_id := seq_len(.n), = label]     label count color_id 1:    red     2        1 2:    red     2        2 3:   blue     1        1 4:  green     3        1 5:  green     3        2 6:  green     3        3 7: orange     1        1 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -