Numerically label every nth group of rows, increasing after each group


I have this code below that creates a new column that labels every group of 6 rows from the beginning to the end of the dataset, increasing in number after each grouping (e.g. 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2).
I was wondering how to modify this code (or if there is a different code that could accomplish the following) so that I could run it over each subject's data, rather than over the entire dataset? In my dataset, each subject has 192 rows, therefore I would like to achieve 32 total groups of 6.

df$newcol = rep(1:ceiling(nrow(df)/6), each = 6)[1:nrow(df)]

Any insight is appreciated!

turn your fixed solution into a function that can work on arbitrary df, then group_modify your target like so

 d$newcol =  rep(1:ceiling(nrow(d)/6), each = 6)[1:nrow(d)]

group_by(iris,Species) %>%
  group_modify(~rep6(.))  # %>% print(n=150)
1 Like

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