Good catch.
If only n_groups is of interest
find_num_grps <- function(N) {
length(which(cumsum(seq(1:N)) <= N))
}
find_num_grps(30)
#> [1] 7
find_num_grps(21)
#> [1] 6
I have a bias against control structures, such as while because from a user-facing perspective R presents as a functional language—f(x)=y. It's almost always better to specify what is desired than how, if for no other reason than that it forces clarification of exactly the outcome being sought.
But, yes, these functions can be used in a loop, but what does that get you that this doesn't?
find_grps <- function(N) {
which(cumsum(seq(1:N)) <= N)
}
find_grps(30)
#> [1] 1 2 3 4 5 6 7
This shows all the intermediate results that could be viewed in a control statement one at a time.