summarizing by group and linking the total group n with individual id

Hello @cactus ,
you could also try this :

dfcolor <- data.frame(
  subjectid = c(1,2,3,4,5,6,7,8,9,10,11),
  grpmonth1 = c("RED", "BLUE", "GREEN", "RED", "GREEN", "RED", "GREEN", "GREEN", "BLUE", "GREEN", "BLUE"),
  grpmonth2 = c("RED", "RED", "GREEN", "RED", "RED", "RED", "GREEN", "GREEN", "RED", "GREEN", "BLUE"),
  grpmonth3 = c("GREEN", "BLUE", "GREEN", "RED", "GREEN", "RED", "GREEN", "BLUE", "RED", "GREEN", "BLUE"),
  grpmonth4 = c("BLUE", "BLUE", "GREEN", "RED", "GREEN", "RED", "RED", "GREEN", "RED", "GREEN", "BLUE"),
  grpmonth5 = c("RED", "BLUE", "RED", "RED", "RED", "RED", "GREEN", "GREEN", "RED", "BLUE", "BLUE"),
  stringsAsFactors = T)

grps <- setdiff(names(dfcolor),c("subjectid"))

for (grp in grps) {
  counts <- table(dfcolor[grp])
  n <- as.numeric(counts[ unlist(dfcolor[grp])])
  dfcolor[paste("n",grp,sep="_")] <- n
}

dfcolor
#>    subjectid grpmonth1 grpmonth2 grpmonth3 grpmonth4 grpmonth5 n_grpmonth1
#> 1          1       RED       RED     GREEN      BLUE       RED           3
#> 2          2      BLUE       RED      BLUE      BLUE      BLUE           3
#> 3          3     GREEN     GREEN     GREEN     GREEN       RED           5
#> 4          4       RED       RED       RED       RED       RED           3
#> 5          5     GREEN       RED     GREEN     GREEN       RED           5
#> 6          6       RED       RED       RED       RED       RED           3
#> 7          7     GREEN     GREEN     GREEN       RED     GREEN           5
#> 8          8     GREEN     GREEN      BLUE     GREEN     GREEN           5
#> 9          9      BLUE       RED       RED       RED       RED           3
#> 10        10     GREEN     GREEN     GREEN     GREEN      BLUE           5
#> 11        11      BLUE      BLUE      BLUE      BLUE      BLUE           3
#>    n_grpmonth2 n_grpmonth3 n_grpmonth4 n_grpmonth5
#> 1            6           5           3           6
#> 2            6           3           3           3
#> 3            4           5           4           6
#> 4            6           3           4           6
#> 5            6           5           4           6
#> 6            6           3           4           6
#> 7            4           5           4           2
#> 8            4           3           4           2
#> 9            6           3           4           6
#> 10           4           5           4           3
#> 11           1           3           3           3
Created on 2021-09-02 by the reprex package (v2.0.0)