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

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -