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))
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))
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
Post a Comment