Assign Color to Every Subject in Group

If I have a dataframe with 100 subjects, and each subject falls within 20 different groups, and each group has between 3-6 subjects.

I have a list of 10 colors (red, green, blue, etc). I want to assign a color to each subject in a group, for example, the first subject in group A is red, second subject in group A is green, third subject in group A is blue, etc. Then first subject in group B is red, second subject in group B is green, third subject in group B is blue, etc.

Can you please help me write a code for this?

Code added:

D<-data.frame(ID = c("01", "03", "04", "07", "08", "05", "10", "09", "12", "11", "16", "17", "15", "19", "26", "25", "20", "32", "28", "29", "31", "34", "35", "36", "37"), Group = c(1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6))
Color<- c("#3366cc","#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00", "#b82e2e", "#316395",'#994499','#22AA99','#AAAA11','#6633CC','#E67300','#8B0707','#651067','#329262','#5574A6','#3B3EAC')

I would create a ranking within each group and join a list of colors to that but it is hard to give an example without seeing an example of the data. Could you post a small example of the data? Just a couple of groups would be enough.

I added an example for the first 25 subjects.

library(dplyr)

D <- data.frame(ID = c("01", "03", "04", "07", "08", "05", "10", "09", "12", "11", "16", "17", "15", 
                       "19", "26", "25", "20", "32", "28", "29", "31", "34", "35", "36", "37"), 
                Group = c(1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6))
Color <- c("#3366cc","#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00", 
           "#b82e2e", "#316395",'#994499','#22AA99','#AAAA11','#6633CC','#E67300','#8B0707','#651067',
           '#329262','#5574A6','#3B3EAC')

D <- D %>% group_by(Group) %>% mutate(Rank = row_number(ID)) %>% arrange(Group, Rank)

ColDF <- data.frame(Rank = 1:20, Color = Color)

D <- inner_join(D, ColDF, by = "Rank")

head(D)
#> # A tibble: 6 x 4
#> # Groups:   Group [2]
#>   ID    Group  Rank Color  
#>   <fct> <dbl> <int> <fct>  
#> 1 01        1     1 #3366cc
#> 2 03        1     2 #dc3912
#> 3 04        1     3 #ff9900
#> 4 05        2     1 #3366cc
#> 5 07        2     2 #dc3912
#> 6 08        2     3 #ff9900

Created on 2019-08-16 by the reprex package (v0.2.1)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.